claude-agent-sdk 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +34 -0
- data/README.md +516 -91
- data/lib/claude_agent_sdk/message_parser.rb +7 -4
- data/lib/claude_agent_sdk/query.rb +91 -4
- data/lib/claude_agent_sdk/subprocess_cli_transport.rb +106 -2
- data/lib/claude_agent_sdk/types.rb +397 -10
- data/lib/claude_agent_sdk/version.rb +1 -1
- data/lib/claude_agent_sdk.rb +9 -0
- metadata +2 -2
data/README.md
CHANGED
|
@@ -1,19 +1,39 @@
|
|
|
1
1
|
# Claude Agent SDK for Ruby
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> **Disclaimer**: This is an **unofficial, community-maintained** Ruby SDK for Claude Agent. It is not officially supported by Anthropic. For official SDK support, see the [Python SDK](https://docs.claude.com/en/api/agent-sdk/python).
|
|
4
4
|
>
|
|
5
5
|
> This implementation is based on the official Python SDK and aims to provide feature parity for Ruby developers. Use at your own risk.
|
|
6
6
|
|
|
7
|
-
Ruby SDK for Claude Agent. See the [Claude Agent SDK documentation](https://docs.anthropic.com/en/docs/claude-code/sdk) for more information.
|
|
8
|
-
|
|
9
7
|
[](https://badge.fury.io/rb/claude-agent-sdk)
|
|
10
8
|
|
|
9
|
+
## Table of Contents
|
|
10
|
+
|
|
11
|
+
- [Installation](#installation)
|
|
12
|
+
- [Quick Start](#quick-start)
|
|
13
|
+
- [Basic Usage: query()](#basic-usage-query)
|
|
14
|
+
- [Client](#client)
|
|
15
|
+
- [Custom Tools (SDK MCP Servers)](#custom-tools-sdk-mcp-servers)
|
|
16
|
+
- [Hooks](#hooks)
|
|
17
|
+
- [Permission Callbacks](#permission-callbacks)
|
|
18
|
+
- [Structured Output](#structured-output)
|
|
19
|
+
- [Budget Control](#budget-control)
|
|
20
|
+
- [Fallback Model](#fallback-model)
|
|
21
|
+
- [Beta Features](#beta-features)
|
|
22
|
+
- [Tools Configuration](#tools-configuration)
|
|
23
|
+
- [Sandbox Settings](#sandbox-settings)
|
|
24
|
+
- [File Checkpointing & Rewind](#file-checkpointing--rewind)
|
|
25
|
+
- [Types](#types)
|
|
26
|
+
- [Error Handling](#error-handling)
|
|
27
|
+
- [Examples](#examples)
|
|
28
|
+
- [Development](#development)
|
|
29
|
+
- [License](#license)
|
|
30
|
+
|
|
11
31
|
## Installation
|
|
12
32
|
|
|
13
33
|
Add this line to your application's Gemfile:
|
|
14
34
|
|
|
15
35
|
```ruby
|
|
16
|
-
gem 'claude-agent-sdk', '~> 0.
|
|
36
|
+
gem 'claude-agent-sdk', '~> 0.4.0'
|
|
17
37
|
```
|
|
18
38
|
|
|
19
39
|
And then execute:
|
|
@@ -45,7 +65,7 @@ end
|
|
|
45
65
|
|
|
46
66
|
## Basic Usage: query()
|
|
47
67
|
|
|
48
|
-
`query()` is a function for querying Claude Code. It yields response messages to a block.
|
|
68
|
+
`query()` is a function for querying Claude Code. It yields response messages to a block.
|
|
49
69
|
|
|
50
70
|
```ruby
|
|
51
71
|
require 'claude_agent_sdk'
|
|
@@ -133,11 +153,66 @@ For a complete example, see [examples/streaming_input_example.rb](examples/strea
|
|
|
133
153
|
|
|
134
154
|
`ClaudeAgentSDK::Client` supports bidirectional, interactive conversations with Claude Code. Unlike `query()`, `Client` enables **custom tools**, **hooks**, and **permission callbacks**, all of which can be defined as Ruby procs/lambdas.
|
|
135
155
|
|
|
136
|
-
**The Client class automatically uses streaming mode** for bidirectional communication, allowing you to send multiple queries dynamically during a single session without closing the connection.
|
|
156
|
+
**The Client class automatically uses streaming mode** for bidirectional communication, allowing you to send multiple queries dynamically during a single session without closing the connection.
|
|
137
157
|
|
|
138
|
-
|
|
158
|
+
### Basic Client Usage
|
|
159
|
+
|
|
160
|
+
```ruby
|
|
161
|
+
require 'claude_agent_sdk'
|
|
162
|
+
require 'async'
|
|
139
163
|
|
|
140
|
-
|
|
164
|
+
Async do
|
|
165
|
+
client = ClaudeAgentSDK::Client.new
|
|
166
|
+
|
|
167
|
+
begin
|
|
168
|
+
# Connect automatically uses streaming mode for bidirectional communication
|
|
169
|
+
client.connect
|
|
170
|
+
|
|
171
|
+
# Send a query
|
|
172
|
+
client.query("What is the capital of France?")
|
|
173
|
+
|
|
174
|
+
# Receive the response
|
|
175
|
+
client.receive_response do |msg|
|
|
176
|
+
if msg.is_a?(ClaudeAgentSDK::AssistantMessage)
|
|
177
|
+
msg.content.each do |block|
|
|
178
|
+
puts block.text if block.is_a?(ClaudeAgentSDK::TextBlock)
|
|
179
|
+
end
|
|
180
|
+
elsif msg.is_a?(ClaudeAgentSDK::ResultMessage)
|
|
181
|
+
puts "Cost: $#{msg.total_cost_usd}" if msg.total_cost_usd
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
ensure
|
|
186
|
+
client.disconnect
|
|
187
|
+
end
|
|
188
|
+
end.wait
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### Advanced Client Features
|
|
192
|
+
|
|
193
|
+
```ruby
|
|
194
|
+
Async do
|
|
195
|
+
client = ClaudeAgentSDK::Client.new
|
|
196
|
+
client.connect
|
|
197
|
+
|
|
198
|
+
# Send interrupt signal
|
|
199
|
+
client.interrupt
|
|
200
|
+
|
|
201
|
+
# Change permission mode during conversation
|
|
202
|
+
client.set_permission_mode('acceptEdits')
|
|
203
|
+
|
|
204
|
+
# Change AI model during conversation
|
|
205
|
+
client.set_model('claude-sonnet-4-5')
|
|
206
|
+
|
|
207
|
+
# Get server initialization info
|
|
208
|
+
info = client.server_info
|
|
209
|
+
puts "Available commands: #{info}"
|
|
210
|
+
|
|
211
|
+
client.disconnect
|
|
212
|
+
end.wait
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Custom Tools (SDK MCP Servers)
|
|
141
216
|
|
|
142
217
|
A **custom tool** is a Ruby proc/lambda that you can offer to Claude, for Claude to invoke as needed.
|
|
143
218
|
|
|
@@ -145,9 +220,7 @@ Custom tools are implemented as in-process MCP servers that run directly within
|
|
|
145
220
|
|
|
146
221
|
**Implementation**: This SDK uses the [official Ruby MCP SDK](https://github.com/modelcontextprotocol/ruby-sdk) (`mcp` gem) internally, providing full protocol compliance while offering a simpler block-based API for tool definition.
|
|
147
222
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
#### Creating a Simple Tool
|
|
223
|
+
### Creating a Simple Tool
|
|
151
224
|
|
|
152
225
|
```ruby
|
|
153
226
|
require 'claude_agent_sdk'
|
|
@@ -182,7 +255,7 @@ Async do
|
|
|
182
255
|
end.wait
|
|
183
256
|
```
|
|
184
257
|
|
|
185
|
-
|
|
258
|
+
### Benefits Over External MCP Servers
|
|
186
259
|
|
|
187
260
|
- **No subprocess management** - Runs in the same process as your application
|
|
188
261
|
- **Better performance** - No IPC overhead for tool calls
|
|
@@ -190,7 +263,7 @@ end.wait
|
|
|
190
263
|
- **Easier debugging** - All code runs in the same process
|
|
191
264
|
- **Direct access** - Tools can directly access your application's state
|
|
192
265
|
|
|
193
|
-
|
|
266
|
+
### Calculator Example
|
|
194
267
|
|
|
195
268
|
```ruby
|
|
196
269
|
# Define calculator tools
|
|
@@ -220,7 +293,7 @@ options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
|
220
293
|
)
|
|
221
294
|
```
|
|
222
295
|
|
|
223
|
-
|
|
296
|
+
### Mixed Server Support
|
|
224
297
|
|
|
225
298
|
You can use both SDK and external MCP servers together:
|
|
226
299
|
|
|
@@ -236,7 +309,7 @@ options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
|
236
309
|
)
|
|
237
310
|
```
|
|
238
311
|
|
|
239
|
-
|
|
312
|
+
### MCP Resources and Prompts
|
|
240
313
|
|
|
241
314
|
SDK MCP servers can also expose **resources** (data sources) and **prompts** (reusable templates):
|
|
242
315
|
|
|
@@ -286,48 +359,13 @@ server = ClaudeAgentSDK.create_sdk_mcp_server(
|
|
|
286
359
|
)
|
|
287
360
|
```
|
|
288
361
|
|
|
289
|
-
For complete examples, see [examples/mcp_resources_prompts_example.rb](examples/mcp_resources_prompts_example.rb).
|
|
290
|
-
|
|
291
|
-
### Basic Client Usage
|
|
292
|
-
|
|
293
|
-
```ruby
|
|
294
|
-
require 'claude_agent_sdk'
|
|
295
|
-
require 'async'
|
|
296
|
-
|
|
297
|
-
Async do
|
|
298
|
-
client = ClaudeAgentSDK::Client.new
|
|
299
|
-
|
|
300
|
-
begin
|
|
301
|
-
# Connect automatically uses streaming mode for bidirectional communication
|
|
302
|
-
client.connect
|
|
303
|
-
|
|
304
|
-
# Send a query
|
|
305
|
-
client.query("What is the capital of France?")
|
|
306
|
-
|
|
307
|
-
# Receive the response
|
|
308
|
-
client.receive_response do |msg|
|
|
309
|
-
if msg.is_a?(ClaudeAgentSDK::AssistantMessage)
|
|
310
|
-
msg.content.each do |block|
|
|
311
|
-
puts block.text if block.is_a?(ClaudeAgentSDK::TextBlock)
|
|
312
|
-
end
|
|
313
|
-
elsif msg.is_a?(ClaudeAgentSDK::ResultMessage)
|
|
314
|
-
puts "Cost: $#{msg.total_cost_usd}" if msg.total_cost_usd
|
|
315
|
-
end
|
|
316
|
-
end
|
|
317
|
-
|
|
318
|
-
ensure
|
|
319
|
-
client.disconnect
|
|
320
|
-
end
|
|
321
|
-
end.wait
|
|
322
|
-
```
|
|
362
|
+
For complete examples, see [examples/mcp_calculator.rb](examples/mcp_calculator.rb) and [examples/mcp_resources_prompts_example.rb](examples/mcp_resources_prompts_example.rb).
|
|
323
363
|
|
|
324
|
-
|
|
364
|
+
## Hooks
|
|
325
365
|
|
|
326
366
|
A **hook** is a Ruby proc/lambda that the Claude Code *application* (*not* Claude) invokes at specific points of the Claude agent loop. Hooks can provide deterministic processing and automated feedback for Claude. Read more in [Claude Code Hooks Reference](https://docs.anthropic.com/en/docs/claude-code/hooks).
|
|
327
367
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
#### Example
|
|
368
|
+
### Example
|
|
331
369
|
|
|
332
370
|
```ruby
|
|
333
371
|
require 'claude_agent_sdk'
|
|
@@ -383,13 +421,13 @@ Async do
|
|
|
383
421
|
end.wait
|
|
384
422
|
```
|
|
385
423
|
|
|
386
|
-
|
|
424
|
+
For more examples, see [examples/hooks_example.rb](examples/hooks_example.rb).
|
|
387
425
|
|
|
388
|
-
|
|
426
|
+
## Permission Callbacks
|
|
389
427
|
|
|
390
|
-
|
|
428
|
+
A **permission callback** is a Ruby proc/lambda that allows you to programmatically control tool execution. This gives you fine-grained control over what tools Claude can use and with what inputs.
|
|
391
429
|
|
|
392
|
-
|
|
430
|
+
### Example
|
|
393
431
|
|
|
394
432
|
```ruby
|
|
395
433
|
require 'claude_agent_sdk'
|
|
@@ -440,41 +478,419 @@ Async do
|
|
|
440
478
|
end.wait
|
|
441
479
|
```
|
|
442
480
|
|
|
443
|
-
|
|
481
|
+
For more examples, see [examples/permission_callback_example.rb](examples/permission_callback_example.rb).
|
|
482
|
+
|
|
483
|
+
## Structured Output
|
|
444
484
|
|
|
445
|
-
The
|
|
485
|
+
Use `output_format` to get validated JSON responses matching a schema. The Claude CLI returns structured output via a `StructuredOutput` tool use block.
|
|
446
486
|
|
|
447
487
|
```ruby
|
|
488
|
+
require 'claude_agent_sdk'
|
|
489
|
+
require 'json'
|
|
490
|
+
|
|
491
|
+
# Define a JSON schema
|
|
492
|
+
schema = {
|
|
493
|
+
type: 'object',
|
|
494
|
+
properties: {
|
|
495
|
+
name: { type: 'string' },
|
|
496
|
+
age: { type: 'integer' },
|
|
497
|
+
skills: { type: 'array', items: { type: 'string' } }
|
|
498
|
+
},
|
|
499
|
+
required: %w[name age skills]
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
503
|
+
output_format: { type: 'json_schema', schema: schema },
|
|
504
|
+
max_turns: 3
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
structured_data = nil
|
|
508
|
+
|
|
509
|
+
ClaudeAgentSDK.query(
|
|
510
|
+
prompt: "Create a profile for a software engineer",
|
|
511
|
+
options: options
|
|
512
|
+
) do |message|
|
|
513
|
+
if message.is_a?(ClaudeAgentSDK::AssistantMessage)
|
|
514
|
+
message.content.each do |block|
|
|
515
|
+
# Structured output comes via StructuredOutput tool use
|
|
516
|
+
if block.is_a?(ClaudeAgentSDK::ToolUseBlock) && block.name == 'StructuredOutput'
|
|
517
|
+
structured_data = block.input
|
|
518
|
+
end
|
|
519
|
+
end
|
|
520
|
+
end
|
|
521
|
+
end
|
|
522
|
+
|
|
523
|
+
if structured_data
|
|
524
|
+
puts "Name: #{structured_data[:name]}"
|
|
525
|
+
puts "Age: #{structured_data[:age]}"
|
|
526
|
+
puts "Skills: #{structured_data[:skills].join(', ')}"
|
|
527
|
+
end
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
For complete examples, see [examples/structured_output_example.rb](examples/structured_output_example.rb).
|
|
531
|
+
|
|
532
|
+
## Budget Control
|
|
533
|
+
|
|
534
|
+
Use `max_budget_usd` to set a spending cap for your queries:
|
|
535
|
+
|
|
536
|
+
```ruby
|
|
537
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
538
|
+
max_budget_usd: 0.10, # Cap at $0.10
|
|
539
|
+
max_turns: 3
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
ClaudeAgentSDK.query(prompt: "Explain recursion", options: options) do |message|
|
|
543
|
+
if message.is_a?(ClaudeAgentSDK::ResultMessage)
|
|
544
|
+
puts "Cost: $#{message.total_cost_usd}"
|
|
545
|
+
end
|
|
546
|
+
end
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
For complete examples, see [examples/budget_control_example.rb](examples/budget_control_example.rb).
|
|
550
|
+
|
|
551
|
+
## Fallback Model
|
|
552
|
+
|
|
553
|
+
Use `fallback_model` to specify a backup model if the primary is unavailable:
|
|
554
|
+
|
|
555
|
+
```ruby
|
|
556
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
557
|
+
model: 'claude-sonnet-4-20250514',
|
|
558
|
+
fallback_model: 'claude-3-5-haiku-20241022'
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
ClaudeAgentSDK.query(prompt: "Hello", options: options) do |message|
|
|
562
|
+
if message.is_a?(ClaudeAgentSDK::AssistantMessage)
|
|
563
|
+
puts "Model used: #{message.model}"
|
|
564
|
+
end
|
|
565
|
+
end
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
For complete examples, see [examples/fallback_model_example.rb](examples/fallback_model_example.rb).
|
|
569
|
+
|
|
570
|
+
## Beta Features
|
|
571
|
+
|
|
572
|
+
Enable experimental features using the `betas` option:
|
|
573
|
+
|
|
574
|
+
```ruby
|
|
575
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
576
|
+
betas: ['context-1m-2025-08-07'] # Extended context window
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
ClaudeAgentSDK.query(prompt: "Analyze this large document...", options: options) do |message|
|
|
580
|
+
puts message
|
|
581
|
+
end
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
Available beta features are listed in the `SDK_BETAS` constant.
|
|
585
|
+
|
|
586
|
+
## Tools Configuration
|
|
587
|
+
|
|
588
|
+
Configure base tools separately from allowed tools:
|
|
589
|
+
|
|
590
|
+
```ruby
|
|
591
|
+
# Using an array of tool names
|
|
592
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
593
|
+
tools: ['Read', 'Edit', 'Bash'] # Base tools available
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
# Using a preset
|
|
597
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
598
|
+
tools: ClaudeAgentSDK::ToolsPreset.new(preset: 'claude_code')
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
# Appending to allowed tools
|
|
602
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
603
|
+
append_allowed_tools: ['Write', 'Bash']
|
|
604
|
+
)
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
## Sandbox Settings
|
|
608
|
+
|
|
609
|
+
Run commands in an isolated sandbox for additional security:
|
|
610
|
+
|
|
611
|
+
```ruby
|
|
612
|
+
sandbox = ClaudeAgentSDK::SandboxSettings.new(
|
|
613
|
+
enabled: true,
|
|
614
|
+
auto_allow_bash_if_sandboxed: true,
|
|
615
|
+
network: ClaudeAgentSDK::SandboxNetworkConfig.new(
|
|
616
|
+
allow_local_binding: true
|
|
617
|
+
)
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
621
|
+
sandbox: sandbox,
|
|
622
|
+
permission_mode: 'acceptEdits'
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
ClaudeAgentSDK.query(prompt: "Run some commands", options: options) do |message|
|
|
626
|
+
puts message
|
|
627
|
+
end
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
## File Checkpointing & Rewind
|
|
631
|
+
|
|
632
|
+
Enable file checkpointing to revert file changes to a previous state:
|
|
633
|
+
|
|
634
|
+
```ruby
|
|
635
|
+
require 'async'
|
|
636
|
+
|
|
448
637
|
Async do
|
|
449
|
-
|
|
450
|
-
|
|
638
|
+
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
639
|
+
enable_file_checkpointing: true,
|
|
640
|
+
permission_mode: 'acceptEdits'
|
|
641
|
+
)
|
|
451
642
|
|
|
452
|
-
|
|
453
|
-
client.
|
|
643
|
+
client = ClaudeAgentSDK::Client.new(options: options)
|
|
644
|
+
client.connect
|
|
454
645
|
|
|
455
|
-
#
|
|
456
|
-
|
|
646
|
+
# Track user message UUIDs for potential rewind
|
|
647
|
+
user_message_uuids = []
|
|
648
|
+
|
|
649
|
+
# First query - create a file
|
|
650
|
+
client.query("Create a test.rb file with some code")
|
|
651
|
+
client.receive_response do |message|
|
|
652
|
+
# Process all message types as needed
|
|
653
|
+
case message
|
|
654
|
+
when ClaudeAgentSDK::UserMessage
|
|
655
|
+
# Capture UUID for rewind capability
|
|
656
|
+
user_message_uuids << message.uuid if message.uuid
|
|
657
|
+
when ClaudeAgentSDK::AssistantMessage
|
|
658
|
+
# Handle assistant responses
|
|
659
|
+
message.content.each do |block|
|
|
660
|
+
puts block.text if block.is_a?(ClaudeAgentSDK::TextBlock)
|
|
661
|
+
end
|
|
662
|
+
when ClaudeAgentSDK::ResultMessage
|
|
663
|
+
puts "Query completed (cost: $#{message.total_cost_usd})"
|
|
664
|
+
end
|
|
665
|
+
end
|
|
457
666
|
|
|
458
|
-
#
|
|
459
|
-
client.
|
|
667
|
+
# Second query - modify the file
|
|
668
|
+
client.query("Modify the test.rb file to add error handling")
|
|
669
|
+
client.receive_response do |message|
|
|
670
|
+
user_message_uuids << message.uuid if message.is_a?(ClaudeAgentSDK::UserMessage) && message.uuid
|
|
671
|
+
end
|
|
460
672
|
|
|
461
|
-
#
|
|
462
|
-
|
|
463
|
-
|
|
673
|
+
# Rewind to the first checkpoint (undoes the second query's changes)
|
|
674
|
+
if user_message_uuids.first
|
|
675
|
+
puts "Rewinding to checkpoint: #{user_message_uuids.first}"
|
|
676
|
+
client.rewind_files(user_message_uuids.first)
|
|
677
|
+
end
|
|
464
678
|
|
|
465
679
|
client.disconnect
|
|
466
|
-
end
|
|
680
|
+
end
|
|
467
681
|
```
|
|
468
682
|
|
|
683
|
+
> **Note:** The `uuid` field on `UserMessage` is populated by the CLI and represents checkpoint identifiers. Rewinding to a UUID restores file state to what it was at that point in the conversation.
|
|
684
|
+
|
|
469
685
|
## Types
|
|
470
686
|
|
|
471
|
-
See [lib/claude_agent_sdk/types.rb](lib/claude_agent_sdk/types.rb) for complete type definitions
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
687
|
+
See [lib/claude_agent_sdk/types.rb](lib/claude_agent_sdk/types.rb) for complete type definitions.
|
|
688
|
+
|
|
689
|
+
### Message Types
|
|
690
|
+
|
|
691
|
+
```ruby
|
|
692
|
+
# Union type of all possible messages
|
|
693
|
+
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
#### UserMessage
|
|
697
|
+
|
|
698
|
+
User input message.
|
|
699
|
+
|
|
700
|
+
```ruby
|
|
701
|
+
class UserMessage
|
|
702
|
+
attr_accessor :content, # String | Array<ContentBlock>
|
|
703
|
+
:uuid, # String | nil - Unique ID for rewind support
|
|
704
|
+
:parent_tool_use_id # String | nil
|
|
705
|
+
end
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
#### AssistantMessage
|
|
709
|
+
|
|
710
|
+
Assistant response message with content blocks.
|
|
711
|
+
|
|
712
|
+
```ruby
|
|
713
|
+
class AssistantMessage
|
|
714
|
+
attr_accessor :content, # Array<ContentBlock>
|
|
715
|
+
:model, # String
|
|
716
|
+
:parent_tool_use_id,# String | nil
|
|
717
|
+
:error # String | nil ('authentication_failed', 'billing_error', 'rate_limit', 'invalid_request', 'server_error', 'unknown')
|
|
718
|
+
end
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
#### SystemMessage
|
|
722
|
+
|
|
723
|
+
System message with metadata.
|
|
724
|
+
|
|
725
|
+
```ruby
|
|
726
|
+
class SystemMessage
|
|
727
|
+
attr_accessor :subtype, # String ('init', etc.)
|
|
728
|
+
:data # Hash
|
|
729
|
+
end
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
#### ResultMessage
|
|
733
|
+
|
|
734
|
+
Final result message with cost and usage information.
|
|
735
|
+
|
|
736
|
+
```ruby
|
|
737
|
+
class ResultMessage
|
|
738
|
+
attr_accessor :subtype, # String
|
|
739
|
+
:duration_ms, # Integer
|
|
740
|
+
:duration_api_ms, # Integer
|
|
741
|
+
:is_error, # Boolean
|
|
742
|
+
:num_turns, # Integer
|
|
743
|
+
:session_id, # String
|
|
744
|
+
:total_cost_usd, # Float | nil
|
|
745
|
+
:usage, # Hash | nil
|
|
746
|
+
:result, # String | nil (final text result)
|
|
747
|
+
:structured_output # Hash | nil (when using output_format)
|
|
748
|
+
end
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
### Content Block Types
|
|
752
|
+
|
|
753
|
+
```ruby
|
|
754
|
+
# Union type of all content blocks
|
|
755
|
+
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
#### TextBlock
|
|
759
|
+
|
|
760
|
+
Text content block.
|
|
761
|
+
|
|
762
|
+
```ruby
|
|
763
|
+
class TextBlock
|
|
764
|
+
attr_accessor :text # String
|
|
765
|
+
end
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
#### ThinkingBlock
|
|
769
|
+
|
|
770
|
+
Thinking content block (for models with extended thinking capability).
|
|
771
|
+
|
|
772
|
+
```ruby
|
|
773
|
+
class ThinkingBlock
|
|
774
|
+
attr_accessor :thinking, # String
|
|
775
|
+
:signature # String
|
|
776
|
+
end
|
|
777
|
+
```
|
|
778
|
+
|
|
779
|
+
#### ToolUseBlock
|
|
780
|
+
|
|
781
|
+
Tool use request block.
|
|
782
|
+
|
|
783
|
+
```ruby
|
|
784
|
+
class ToolUseBlock
|
|
785
|
+
attr_accessor :id, # String
|
|
786
|
+
:name, # String
|
|
787
|
+
:input # Hash
|
|
788
|
+
end
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
#### ToolResultBlock
|
|
792
|
+
|
|
793
|
+
Tool execution result block.
|
|
794
|
+
|
|
795
|
+
```ruby
|
|
796
|
+
class ToolResultBlock
|
|
797
|
+
attr_accessor :tool_use_id, # String
|
|
798
|
+
:content, # String | Array<Hash> | nil
|
|
799
|
+
:is_error # Boolean | nil
|
|
800
|
+
end
|
|
801
|
+
```
|
|
802
|
+
|
|
803
|
+
### Error Types
|
|
804
|
+
|
|
805
|
+
```ruby
|
|
806
|
+
# Base exception class for all SDK errors
|
|
807
|
+
class ClaudeSDKError < StandardError; end
|
|
808
|
+
|
|
809
|
+
# Raised when Claude Code CLI is not found
|
|
810
|
+
class CLINotFoundError < CLIConnectionError
|
|
811
|
+
# @param message [String] Error message (default: "Claude Code not found")
|
|
812
|
+
# @param cli_path [String, nil] Optional path to the CLI that was not found
|
|
813
|
+
end
|
|
814
|
+
|
|
815
|
+
# Raised when connection to Claude Code fails
|
|
816
|
+
class CLIConnectionError < ClaudeSDKError; end
|
|
817
|
+
|
|
818
|
+
# Raised when the Claude Code process fails
|
|
819
|
+
class ProcessError < ClaudeSDKError
|
|
820
|
+
attr_reader :exit_code, # Integer | nil
|
|
821
|
+
:stderr # String | nil
|
|
822
|
+
end
|
|
823
|
+
|
|
824
|
+
# Raised when JSON parsing fails
|
|
825
|
+
class CLIJSONDecodeError < ClaudeSDKError
|
|
826
|
+
attr_reader :line, # String - The line that failed to parse
|
|
827
|
+
:original_error # Exception - The original JSON decode exception
|
|
828
|
+
end
|
|
829
|
+
|
|
830
|
+
# Raised when message parsing fails
|
|
831
|
+
class MessageParseError < ClaudeSDKError
|
|
832
|
+
attr_reader :data # Hash | nil
|
|
833
|
+
end
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
### Configuration Types
|
|
837
|
+
|
|
838
|
+
| Type | Description |
|
|
839
|
+
|------|-------------|
|
|
840
|
+
| `ClaudeAgentOptions` | Main configuration for queries and clients |
|
|
841
|
+
| `HookMatcher` | Hook configuration with matcher pattern and timeout |
|
|
842
|
+
| `PermissionResultAllow` | Permission callback result to allow tool use |
|
|
843
|
+
| `PermissionResultDeny` | Permission callback result to deny tool use |
|
|
844
|
+
| `AgentDefinition` | Agent definition with description, prompt, tools, model |
|
|
845
|
+
| `McpStdioServerConfig` | MCP server config for stdio transport |
|
|
846
|
+
| `McpSSEServerConfig` | MCP server config for SSE transport |
|
|
847
|
+
| `McpHttpServerConfig` | MCP server config for HTTP transport |
|
|
848
|
+
| `SdkPluginConfig` | SDK plugin configuration |
|
|
849
|
+
| `SandboxSettings` | Sandbox settings for isolated command execution |
|
|
850
|
+
| `SandboxNetworkConfig` | Network configuration for sandbox |
|
|
851
|
+
| `SandboxIgnoreViolations` | Configure which sandbox violations to ignore |
|
|
852
|
+
| `SystemPromptPreset` | System prompt preset configuration |
|
|
853
|
+
| `ToolsPreset` | Tools preset configuration for base tools selection |
|
|
854
|
+
|
|
855
|
+
### Constants
|
|
856
|
+
|
|
857
|
+
| Constant | Description |
|
|
858
|
+
|----------|-------------|
|
|
859
|
+
| `SDK_BETAS` | Available beta features (e.g., `"context-1m-2025-08-07"`) |
|
|
860
|
+
| `PERMISSION_MODES` | Available permission modes |
|
|
861
|
+
| `SETTING_SOURCES` | Available setting sources |
|
|
862
|
+
| `HOOK_EVENTS` | Available hook events |
|
|
863
|
+
| `ASSISTANT_MESSAGE_ERRORS` | Possible error types in AssistantMessage |
|
|
475
864
|
|
|
476
865
|
## Error Handling
|
|
477
866
|
|
|
867
|
+
### AssistantMessage Errors
|
|
868
|
+
|
|
869
|
+
`AssistantMessage` includes an `error` field for API-level errors:
|
|
870
|
+
|
|
871
|
+
```ruby
|
|
872
|
+
ClaudeAgentSDK.query(prompt: "Hello") do |message|
|
|
873
|
+
if message.is_a?(ClaudeAgentSDK::AssistantMessage) && message.error
|
|
874
|
+
case message.error
|
|
875
|
+
when 'rate_limit'
|
|
876
|
+
puts "Rate limited - retry after delay"
|
|
877
|
+
when 'authentication_failed'
|
|
878
|
+
puts "Check your API key"
|
|
879
|
+
when 'billing_error'
|
|
880
|
+
puts "Check your billing status"
|
|
881
|
+
when 'invalid_request'
|
|
882
|
+
puts "Invalid request format"
|
|
883
|
+
when 'server_error'
|
|
884
|
+
puts "Server error - retry later"
|
|
885
|
+
end
|
|
886
|
+
end
|
|
887
|
+
end
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
For complete examples, see [examples/error_handling_example.rb](examples/error_handling_example.rb).
|
|
891
|
+
|
|
892
|
+
### Exception Handling
|
|
893
|
+
|
|
478
894
|
```ruby
|
|
479
895
|
require 'claude_agent_sdk'
|
|
480
896
|
|
|
@@ -491,13 +907,16 @@ rescue ClaudeAgentSDK::CLIJSONDecodeError => e
|
|
|
491
907
|
end
|
|
492
908
|
```
|
|
493
909
|
|
|
494
|
-
Error
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
910
|
+
### Error Types
|
|
911
|
+
|
|
912
|
+
| Error | Description |
|
|
913
|
+
|-------|-------------|
|
|
914
|
+
| `ClaudeSDKError` | Base error for all SDK errors |
|
|
915
|
+
| `CLINotFoundError` | Claude Code not installed |
|
|
916
|
+
| `CLIConnectionError` | Connection issues |
|
|
917
|
+
| `ProcessError` | Process failed (includes `exit_code` and `stderr`) |
|
|
918
|
+
| `CLIJSONDecodeError` | JSON parsing issues |
|
|
919
|
+
| `MessageParseError` | Message parsing issues |
|
|
501
920
|
|
|
502
921
|
See [lib/claude_agent_sdk/errors.rb](lib/claude_agent_sdk/errors.rb) for all error types.
|
|
503
922
|
|
|
@@ -507,15 +926,21 @@ See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-co
|
|
|
507
926
|
|
|
508
927
|
## Examples
|
|
509
928
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
929
|
+
| Example | Description |
|
|
930
|
+
|---------|-------------|
|
|
931
|
+
| [examples/quick_start.rb](examples/quick_start.rb) | Basic `query()` usage with options |
|
|
932
|
+
| [examples/client_example.rb](examples/client_example.rb) | Interactive Client usage |
|
|
933
|
+
| [examples/streaming_input_example.rb](examples/streaming_input_example.rb) | Streaming input for multi-turn conversations |
|
|
934
|
+
| [examples/mcp_calculator.rb](examples/mcp_calculator.rb) | Custom tools with SDK MCP servers |
|
|
935
|
+
| [examples/mcp_resources_prompts_example.rb](examples/mcp_resources_prompts_example.rb) | MCP resources and prompts |
|
|
936
|
+
| [examples/hooks_example.rb](examples/hooks_example.rb) | Using hooks to control tool execution |
|
|
937
|
+
| [examples/permission_callback_example.rb](examples/permission_callback_example.rb) | Dynamic tool permission control |
|
|
938
|
+
| [examples/structured_output_example.rb](examples/structured_output_example.rb) | JSON schema structured output |
|
|
939
|
+
| [examples/budget_control_example.rb](examples/budget_control_example.rb) | Budget control with `max_budget_usd` |
|
|
940
|
+
| [examples/fallback_model_example.rb](examples/fallback_model_example.rb) | Fallback model configuration |
|
|
941
|
+
| [examples/advanced_hooks_example.rb](examples/advanced_hooks_example.rb) | Typed hook inputs/outputs |
|
|
942
|
+
| [examples/error_handling_example.rb](examples/error_handling_example.rb) | Error handling with `AssistantMessage.error` |
|
|
943
|
+
| [examples/extended_thinking_example.rb](examples/extended_thinking_example.rb) | Extended thinking (API parity) |
|
|
519
944
|
|
|
520
945
|
## Development
|
|
521
946
|
|