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, RateLimitEvent, ResultMessage, SandboxIgnoreViolations, SandboxNetworkConfig, SandboxSettings, SdkMcpPrompt, SdkMcpResource, SdkMcpServer, SdkMcpTool, SdkPluginConfig, SessionStartHookSpecificOutput, StopHookInput, StreamEvent, SubagentStartHookInput, SubagentStartHookSpecificOutput, SubagentStopHookInput, SubprocessCLITransport, SyncHookJSONOutput, SystemMessage, SystemPromptPreset, TextBlock, ThinkingBlock, ThinkingConfigAdaptive, ThinkingConfigDisabled, ThinkingConfigEnabled, 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.7.1'
Class Method Summary collapse
-
.configuration ⇒ Configuration
Get the configuration object.
-
.configure {|Configuration| ... } ⇒ Object
Configure the SDK with default options.
-
.create_prompt(name:, description: nil, arguments: nil, &generator) ⇒ SdkMcpPrompt
Helper function to create a prompt definition.
-
.create_resource(uri:, name:, description: nil, mime_type: nil, &reader) ⇒ SdkMcpResource
Helper function to create a resource definition.
-
.create_sdk_mcp_server(name:, version: '1.0.0', tools: [], resources: [], prompts: []) ⇒ Hash
Create an SDK MCP server.
-
.create_tool(name, description, input_schema, annotations: nil, &handler) ⇒ SdkMcpTool
Helper function to create a tool definition.
-
.default_options ⇒ Hash
Get merged default options for use with ClaudeAgentOptions.
-
.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.
-
.query(prompt:, options: nil) {|Message| ... } ⇒ Enumerator
Query Claude Code for one-shot or unidirectional streaming interactions.
-
.reset_configuration ⇒ Object
Reset configuration to defaults (useful for testing).
Class Method Details
.configuration ⇒ Configuration
Get the configuration object
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
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
503 504 505 506 507 508 509 510 511 512 |
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 503 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
445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 445 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
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 555 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, annotations: nil, &handler) ⇒ SdkMcpTool
Helper function to create a tool definition
392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 392 def self.create_tool(name, description, input_schema, annotations: nil, &handler) raise ArgumentError, 'Block required for tool handler' unless handler SdkMcpTool.new( name: name, description: description, input_schema: input_schema, handler: handler, annotations: annotations ) end |
.default_options ⇒ Hash
Get merged default options for use with ClaudeAgentOptions
70 71 72 |
# File 'lib/claude_agent_sdk/configuration.rb', line 70 def configuration. || {} 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.
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/claude_agent_sdk.rb', line 61 def self.query(prompt:, options: nil, &block) return enum_for(:query, prompt: prompt, options: ) unless block ||= ClaudeAgentOptions.new = .dup_with(env: (.env || {}).merge('CLAUDE_CODE_ENTRYPOINT' => 'sdk-rb')) Async do # Always use streaming mode with control protocol (matches Python SDK). # This sends agents via initialize request instead of CLI args, # avoiding OS ARG_MAX limits. transport = SubprocessCLITransport.new() begin transport.connect # Extract SDK MCP servers sdk_mcp_servers = {} if .mcp_servers.is_a?(Hash) .mcp_servers.each do |name, config| sdk_mcp_servers[name] = config[:instance] if config.is_a?(Hash) && config[:type] == 'sdk' end end # Create Query handler for control protocol query_handler = Query.new( transport: transport, is_streaming_mode: true, agents: .agents, sdk_mcp_servers: sdk_mcp_servers ) # Start reading messages in background query_handler.start # Initialize the control protocol (sends agents) query_handler.initialize_protocol # Send prompt(s) as user messages, then close stdin if prompt.is_a?(String) = { type: 'user', message: { role: 'user', content: prompt }, parent_tool_use_id: nil, session_id: 'default' } transport.write(JSON.generate() + "\n") transport.end_input elsif prompt.is_a?(Enumerator) || prompt.respond_to?(:each) Async do begin prompt.each do || transport.write() end ensure transport.end_input end end end # Read and yield messages from the query handler (filters out control messages) query_handler. do |data| = MessageParser.parse(data) block.call() end ensure # query_handler.close stops the background read task and closes the transport if query_handler query_handler.close else transport.close end end end.wait end |
.reset_configuration ⇒ Object
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 |