claude-sdk 2.0.0

Native Rust SDK for the Claude API with streaming support and tool execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# Claude SDK for Rust

[![Crates.io](https://img.shields.io/badge/version-1.0.0-blue)](https://crates.io/crates/claude-sdk)
[![Documentation](https://docs.rs/claude-sdk/badge.svg)](https://docs.rs/claude-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A **complete, production-ready** Rust SDK for Claude with full API coverage. Built for [Colony Shell](https://github.com/mcfearsome/colony-shell) but usable standalone.

## ⚡ What Makes This Special

- **100% Feature Complete** - Every Claude API feature implemented
- **Both Platforms** - Anthropic API + AWS Bedrock with unified interface
- **Production Ready** - 90 tests, retry logic, error handling, token counting
- **Developer Experience** - Interactive REPL, auto-changelog, pre-commit hooks
- **Type Safe** - Leverage Rust's type system for correctness
- **Zero Cost** - Idiomatic async Rust with no runtime overhead

---

## 🚀 Features

### Core API
✅ **Streaming & Non-streaming** - SSE streams + complete responses
✅ **Error Handling** - Comprehensive error taxonomy with retry logic
✅ **Exponential Backoff** - Automatic retry on rate limits (429) and server errors (5xx)
✅ **Token Counting** - Accurate context window management with tiktoken-rs

### Intelligence & Tools
✅ **Tool Use** - Programmatic calling, parallel execution, input examples (beta)
✅ **Tool Choice** - Force specific tools (auto/any/tool/none)
✅ **Conversations** - Multi-turn state management with ConversationBuilder
✅ **Extended Thinking** - Step-by-step reasoning (thinking blocks with signatures)
✅ **Effort Control** - Token efficiency (high/medium/low for Opus 4.5)

### Content Types
✅ **Text** - Standard messages with optional citations
✅ **Images** - Vision support (base64, URL, or file_id)
✅ **Documents** - PDFs and text files with citations
✅ **Search Results** - RAG with automatic source attribution
✅ **Thinking Blocks** - Extended reasoning (including redacted)

### Cost Optimization
✅ **Prompt Caching** - 90% cost reduction on cached content (system prompts, tools, docs)
✅ **Batch Processing** - 50% discount for async bulk requests (up to 100K requests)
✅ **Files API** - Upload once, reference many times

### Platform Support
✅ **Anthropic API** - Full support including all beta features
✅ **AWS Bedrock** - Complete implementation with streaming
✅ **Regional Endpoints** - standard/global/us/eu/ap prefixes

### Developer Tools
✅ **Interactive REPL** - Full terminal UI with streaming, token display, backend switching
✅ **Auto-Changelog** - Uses Claude to generate changelog from git commits
✅ **Pre-commit Hooks** - Automated quality checks (test, clippy, fmt, docs)
✅ **CI/CD** - GitHub Actions for testing, releases, upstream monitoring
✅ **System Prompts** - Battle-tested prompts including Claude Code

### Advanced Features
✅ **Structured Outputs** - Forced JSON extraction with schema validation
✅ **Context Validation** - Proactive window checking (200K/1M tokens)
✅ **Model Registry** - 9 models with full metadata, constraints, pricing
✅ **Model Capabilities** - Track extended context, effort support, thinking support

---

## 📦 Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
claude-sdk = "1.0"
tokio = { version = "1", features = ["full"] }

# Optional features
claude-sdk = { version = "1.0", features = ["bedrock", "repl"] }
```

**Features:**
- `anthropic` (default) - Anthropic API support
- `bedrock` - AWS Bedrock support
- `repl` - Interactive REPL binary
- `full` - All features enabled

---

## 🎯 Quick Start

### Basic Chat

```rust
use claude_sdk::{ClaudeClient, Message, MessagesRequest, models};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);

    let request = MessagesRequest::new(
        models::CLAUDE_SONNET_4_5.anthropic_id,
        1024,
        vec![Message::user("Explain quantum entanglement")],
    );

    let response = client.send_message(request).await?;

    for content in &response.content {
        if let claude_sdk::ContentBlock::Text { text, .. } = content {
            println!("{}", text);
        }
    }

    Ok(())
}
```

### Streaming Responses

```rust
use claude_sdk::{ClaudeClient, Message, MessagesRequest, StreamEvent};
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClaudeClient::anthropic(
        std::env::var("ANTHROPIC_API_KEY")?
    );

    let request = MessagesRequest::new(
        claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
        1024,
        vec![Message::user("Tell me a story")],
    );

    let mut stream = client.send_streaming(request).await?;

    while let Some(event) = stream.next().await {
        match event? {
            StreamEvent::ContentBlockDelta { delta, .. } => {
                if let Some(text) = delta.text() {
                    print!("{}", text);
                }
            }
            StreamEvent::MessageStop => break,
            _ => {}
        }
    }

    Ok(())
}
```

### AWS Bedrock

Same API works with AWS Bedrock:

```rust
use claude_sdk::{ClaudeClient, MessagesRequest, Message, models};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Uses AWS_PROFILE or default credential chain
    let client = ClaudeClient::bedrock("us-east-1").await?;

    let request = MessagesRequest::new(
        models::CLAUDE_SONNET_4_5.anthropic_id,  // Auto-converts to Bedrock format
        1024,
        vec![Message::user("Hello from Bedrock!")],
    );

    let response = client.send_message(request).await?;
    // Works identically to Anthropic API!

    Ok(())
}
```

### Tool Use

```rust
use claude_sdk::{ConversationBuilder, Tool, models};
use serde_json::json;

let mut conversation = ConversationBuilder::new()
    .with_cached_system("You are a helpful assistant")  // Cached for 5min!
    .with_cached_tool(Tool {
        name: "get_weather".into(),
        description: "Get current weather".into(),
        input_schema: json!({"type": "object", "properties": {
            "location": {"type": "string"}
        }}),
        disable_user_input: Some(true),  // Programmatic
        input_examples: None,
        cache_control: None,
    });

conversation.add_user_message("What's the weather in Tokyo?");

// Claude will request tool use automatically
let request = conversation.build(models::CLAUDE_SONNET_4_5.anthropic_id, 1024);
```

### Extended Thinking

```rust
let request = MessagesRequest::new(
    models::CLAUDE_SONNET_4_5.anthropic_id,
    16000,
    vec![Message::user("Solve this complex math problem...")],
)
.with_thinking(10_000);  // 10K token budget for reasoning

// Response includes thinking blocks showing step-by-step reasoning
```

### Batch Processing (50% Discount!)

```rust
use claude_sdk::batch::{BatchClient, BatchRequest};

let batch_client = BatchClient::new(api_key);

let requests = vec![
    BatchRequest {
        custom_id: "req-1".into(),
        params: MessagesRequest::new(/*...*/),
    },
    // ... up to 100,000 requests
];

let batch = batch_client.create(requests).await?;
let completed = batch_client.wait_for_completion(&batch.id).await?;

// 50% cost reduction on all tokens!
```

### Retry Logic for Production

```rust
use claude_sdk::{ClaudeClient, MessagesRequest, Message};
use claude_sdk::retry::RetryConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClaudeClient::anthropic(
        std::env::var("ANTHROPIC_API_KEY")?
    );

    let request = MessagesRequest::new(
        claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
        1024,
        vec![Message::user("Hello!")],
    );

    // Configure retry behavior
    let retry_config = RetryConfig::new()
        .with_max_attempts(5)
        .with_initial_backoff(std::time::Duration::from_secs(1))
        .with_max_backoff(std::time::Duration::from_secs(60));

    // Automatically retries on rate limits and server errors
    let response = client.send_message_with_retry(request, retry_config).await?;

    Ok(())
}
```

## Examples

Run the examples with your API key:

```bash
export ANTHROPIC_API_KEY="your-api-key"
cargo run --example simple_chat
cargo run --example streaming_chat
cargo run --example tool_use
cargo run --example prompt_caching
```

Available examples:
- `simple_chat` - Basic message sending with complete responses
- `streaming_chat` - Real-time streaming responses with token display
- `tool_use` - Tool definitions, multi-turn conversations, programmatic tool calling
- `prompt_caching` - Cost reduction with prompt caching (90% savings on cached tokens)

---

## 🤖 Supported Models

All Claude 4.5, 4.x, and 3.x models supported with full metadata:

| Model | Context | Output | Extended Context | Thinking | Effort |
|-------|---------|--------|------------------|----------|--------|
| **Claude Sonnet 4.5** | 200K | 64K | ✅ 1M |||
| **Claude Haiku 4.5** | 200K | 64K ||||
| **Claude Opus 4.5** | 200K | 64K ||||
| Claude Opus 4.1 | 200K | 32K ||||
| Claude Sonnet 4 | 200K | 64K | ✅ 1M |||
| Others | 200K | varies | varies | varies ||

**Model Registry Includes:**
- Context windows & output limits
- Extended context support (1M)
- Thinking capability
- Effort parameter support
- Pricing per million tokens
- Bedrock & Vertex AI IDs
- Regional endpoint prefixes

---

## ✅ Complete API Coverage

**Messages API: 100%**
- [x] Non-streaming & streaming
- [x] System prompts (cached & non-cached)
- [x] Multi-turn conversations
- [x] Stop reasons (end_turn, max_tokens, stop_sequence, tool_use, pause_turn)

**Content Types: 100%**
- [x] Text (with citations)
- [x] Images (base64, URL, file_id)
- [x] Documents (PDFs, text with citations)
- [x] Search Results (RAG with auto-citations)
- [x] Tool Use & Tool Results
- [x] Thinking & Redacted Thinking

**Tool Use: 100%**
- [x] Tool definitions with JSON schemas
- [x] Programmatic calling (disable_user_input)
- [x] Tool choice (auto/any/tool/none)
- [x] Parallel tool use (configurable)
- [x] Input examples (beta)
- [x] Tool result error handling

**Platform: 100%**
- [x] Anthropic API (complete)
- [x] AWS Bedrock (streaming + non-streaming)
- [x] Regional endpoints (standard/global/us/eu/ap)
- [x] Automatic model ID conversion

**Optimization: 100%**
- [x] Prompt caching (90% savings)
- [x] Batch processing (50% discount)
- [x] Token counting (tiktoken-rs)
- [x] Context validation (200K/1M)
- [x] Retry logic with backoff
- [x] Effort control (Opus 4.5)

**Advanced: 100%**
- [x] Extended thinking (reasoning blocks)
- [x] Files API (upload/download/manage)
- [x] Structured outputs (forced JSON)
- [x] Vision (image analysis)
- [x] Citations (automatic source attribution)

**Developer Tools: 100%**
- [x] Interactive REPL
- [x] Token counting display
- [x] Conversation save/load
- [x] Auto-changelog generator
- [x] Pre-commit hooks
- [x] CI/CD pipelines
- [x] System prompts (Claude Code)

---

## 🎉 Development Status: v1.0.0 - COMPLETE

**All Features Implemented: 22/22 (100%)**

✅ Core SDK (17/17)
✅ Advanced Features (5/5)
✅ 90 tests passing
✅ Zero technical debt
✅ Production ready

**What This Means:**
- Every documented Claude API feature is implemented
- Both Anthropic and AWS Bedrock fully supported
- All content types (text, image, document, search, thinking)
- All optimization features (caching, batching, retry)
- Complete developer tooling (REPL, hooks, CI/CD)
- Ready for immediate production use

---

## 💡 Why Use This SDK?

**vs. Official SDKs (TypeScript/Python):**
- **Type Safety** - Rust's type system catches errors at compile time
-**Model Registry** - Full metadata with constraints and validation
-**Unified Bedrock** - Same API for both platforms
-**System Prompts** - Pre-built prompts (Claude Code, RAG, coding, etc.)
-**Better Regional Support** - First-class Bedrock endpoint handling
-**Performance** - Zero-cost abstractions, no GC pauses
-**Memory Safety** - No segfaults, no undefined behavior

**vs. Building Your Own:**
- **Complete** - Every API feature implemented
-**Tested** - 90 tests covering all features
-**Maintained** - Auto-monitoring for upstream changes
-**Documented** - Full API docs + examples
-**Production Ready** - Error handling, retry logic, validation

**Perfect For:**
- 🦀 Rust applications needing Claude integration
- 🤖 Building AI agents (like Colony Shell)
- 🏢 Enterprise apps needing AWS Bedrock
- 📊 Batch processing workloads (50% savings)
- 💰 Cost-sensitive applications (caching, batching)

---

## 📁 Project Structure

```
claude-agent-sdk-rust/
├── src/
│   ├── lib.rs              # Public API & re-exports
│   ├── client.rs           # HTTP client (Anthropic + Bedrock)
│   ├── conversation.rs     # ConversationBuilder
│   ├── types.rs            # Request/response types (400+ lines)
│   ├── error.rs            # Error taxonomy
│   ├── models.rs           # Model registry (9 models)
│   ├── streaming.rs        # SSE event types
│   ├── tokens.rs           # Token counting (tiktoken-rs)
│   ├── retry.rs            # Exponential backoff
│   ├── files.rs            # Files API client
│   ├── batch.rs            # Batch processing
│   ├── prompts.rs          # System prompts (Claude Code, etc.)
│   ├── structured.rs       # Structured output helpers
│   └── bin/
│       ├── claude-repl.rs  # Interactive REPL (440+ lines)
│       └── update-changelog.rs  # Changelog generator
├── examples/
│   ├── simple_chat.rs      # Basic non-streaming
│   ├── streaming_chat.rs   # Real-time streaming
│   ├── tool_use.rs         # Multi-turn with tools
│   └── prompt_caching.rs   # Cost optimization
├── .github/workflows/
│   ├── ci.yml              # PR checks
│   ├── release.yml         # Auto-publish
│   └── upstream-check.yml  # Model monitoring
├── hooks/
│   └── pre-commit          # Quality checks
├── scripts/
│   └── install-hooks.sh    # Hook installer
├── .claude/system/
│   ├── features.json       # Feature tracking (22 features)
│   ├── future-features.json # Advanced features
│   └── history.txt         # Development log
├── CHANGELOG.md            # Keep a Changelog format
├── CONTRIBUTING.md         # Development guide
├── RELEASE.md              # Release process
├── ROADMAP.md              # Feature roadmap
└── README.md               # This file
```

## Development Setup

### Install Git Hooks

We use pre-commit hooks to ensure code quality. Install them with:

```bash
./scripts/install-hooks.sh
```

The pre-commit hook automatically runs:
- `cargo test` - All tests must pass
- `cargo clippy -- -D warnings` - No clippy warnings allowed
- `cargo fmt --check` - Code must be formatted
- `cargo doc` - Documentation must build

To bypass the hook (not recommended): `git commit --no-verify`

### Running Checks Manually

```bash
# Run all checks
cargo test --all-features
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
cargo doc --no-deps --all-features

# Auto-fix formatting
cargo fmt --all
```

### Developer Tools

**Interactive REPL:**

Test the SDK interactively with a full-featured terminal interface:

```bash
export ANTHROPIC_API_KEY="your-api-key"
cargo run --features repl --bin claude-repl
```

Features:
- Real-time streaming responses
- Multi-turn conversations
- Token counting in prompt
- Slash commands (/help, /save, /load, /tokens, /model, /backend)
- Backend switching (Anthropic ↔ Bedrock)
- Conversation save/load

**Automated Changelog Generation:**

Use Claude to generate changelog entries from git commits:

```bash
export ANTHROPIC_API_KEY="your-api-key"
cargo run --bin update-changelog
```

This analyzes commits since the last release and generates Keep a Changelog format entries.

---

## 🤝 Contributing

This project is **feature-complete** at v1.0.0, but we welcome:
- 🐛 Bug reports and fixes
- 📝 Documentation improvements
- ✨ Additional examples
- 🔧 Performance optimizations

See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines.

### Development

```bash
# Setup
git clone https://github.com/mcfearsome/claude-agent-sdk-rust
cd claude-agent-sdk-rust
./scripts/install-hooks.sh

# Run tests
cargo test --all-features

# Quality checks
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
cargo doc --no-deps
```

---

## 📚 Documentation

- [API Documentation]https://docs.rs/claude-sdk - Full API reference
- [Examples]./examples/ - Working code examples
- [ROADMAP.md]./ROADMAP.md - Feature tracking & future plans
- [CHANGELOG.md]./CHANGELOG.md - Version history
- [CONTRIBUTING.md]./CONTRIBUTING.md - Development guide
- [RELEASE.md]./RELEASE.md - Release process

**Official Claude Resources:**
- [Claude API Docs]https://platform.claude.com/docs
- [Messages API]https://platform.claude.com/docs/en/api/messages
- [Tool Use Guide]https://platform.claude.com/docs/en/agents-and-tools/tool-use
- [Extended Thinking]https://platform.claude.com/docs/en/build-with-claude/extended-thinking
- [Batch Processing]https://platform.claude.com/docs/en/build-with-claude/batch-processing

---

## 🎯 Design Principles

1. **API Compliance** - Match official Claude API exactly
2. **Type Safety** - Leverage Rust's type system for correctness
3. **Zero Cost** - Idiomatic async Rust with no runtime overhead
4. **Platform Agnostic** - Same API for Anthropic & Bedrock
5. **Production Ready** - Comprehensive error handling, retry logic, validation
6. **Developer Friendly** - Clear APIs, good docs, helpful tools

---

## 🏆 Status

**Version:** 1.0.0
**Status:** Production Ready ✅
**Features:** 22/22 (100%)
**Tests:** 90 passing
**Platforms:** Anthropic + AWS Bedrock

**Built for:** [Colony Shell](https://github.com/mcfearsome/colony-shell) F015 - Claude ADK Integration

---

## 📄 License

MIT License - See [LICENSE](LICENSE) for details

---

## 🙏 Acknowledgments

Built with the official [Claude API](https://platform.claude.com/docs) and inspired by:
- [anthropic-sdk-typescript]https://github.com/anthropics/anthropic-sdk-typescript
- [anthropic-sdk-python]https://github.com/anthropics/anthropic-sdk-python

Special thanks to Anthropic for creating Claude and maintaining excellent API documentation.