claude-sdk 1.1.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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
//! Type definitions for Claude API requests and responses.
//!
//! This module contains all the core types used for communicating with the Claude API:
//!
//! - [`MessagesRequest`] - The main request type for sending messages
//! - [`MessagesResponse`] - Response from the Messages API
//! - [`Message`] - Conversation messages with user/assistant roles
//! - [`ContentBlock`] - Text, images, documents, tool calls, and more
//! - [`Tool`] - Tool definitions for function calling
//! - [`ToolChoice`] - Control how Claude uses tools
//!
//! # Example
//!
//! ```rust
//! use claude_sdk::types::{MessagesRequest, Message, Tool, ToolChoice};
//! use serde_json::json;
//!
//! // Create a basic request
//! let request = MessagesRequest::new(
//!     "claude-sonnet-4-5-20250929",
//!     1024,
//!     vec![Message::user("Hello!")],
//! )
//! .with_system("You are a helpful assistant.")
//! .with_temperature(0.7);
//! ```

use serde::{Deserialize, Serialize};

/// Role in a conversation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Assistant,
}

/// Content block in a message
///
/// Known content block types are deserialized into their respective variants.
/// Unrecognized types (e.g., new API features) are captured in [`ContentBlock::Unknown`]
/// instead of causing a deserialization error.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// Text content
    Text {
        text: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
        /// Citations (appears in responses when using search_result blocks)
        #[serde(skip_serializing_if = "Option::is_none")]
        citations: Option<Vec<Citation>>,
    },
    /// Image content
    Image {
        source: ImageSource,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Document content (PDFs, text files)
    ///
    /// Requires beta header: `anthropic-beta: files-api-2025-04-14`
    Document {
        source: DocumentSource,
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        context: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        citations: Option<CitationConfig>,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Tool use request from the assistant
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Tool result from the user
    ToolResult {
        tool_use_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        content: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
    },
    /// Thinking block from extended thinking
    ///
    /// Contains Claude's step-by-step reasoning process.
    /// Appears when extended thinking is enabled.
    Thinking {
        thinking: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
    },
    /// Redacted thinking block
    ///
    /// Contains encrypted thinking that was flagged by safety systems.
    /// Must be passed back unmodified in multi-turn conversations.
    RedactedThinking { data: String },
    /// Search result for RAG with automatic citations
    ///
    /// Supported in: Opus 4.5, Opus 4.1, Opus 4, Sonnet 4.5, Sonnet 4, Haiku 3.5
    SearchResult {
        source: String,
        title: String,
        content: Vec<TextBlock>,
        #[serde(skip_serializing_if = "Option::is_none")]
        citations: Option<CitationConfig>,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Unknown content block type (forward compatibility)
    ///
    /// When the API returns a content block type this SDK doesn't
    /// recognize, it's captured here rather than causing a deserialization error.
    #[serde(untagged)]
    Unknown {
        /// The `type` field value
        block_type: String,
        /// Raw JSON of the unknown block
        data: serde_json::Value,
    },
}

/// Private helper enum for deserialization of known ContentBlock variants.
///
/// Mirrors all known variants of [`ContentBlock`] exactly, with derived
/// `Deserialize`. Used by the custom `Deserialize` impl on `ContentBlock` to
/// avoid infinite recursion (since `ContentBlock` can't derive `Deserialize`
/// due to the `Unknown` catch-all variant needing to capture raw JSON data).
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ContentBlockHelper {
    Text {
        text: String,
        cache_control: Option<CacheControl>,
        citations: Option<Vec<Citation>>,
    },
    Image {
        source: ImageSource,
        cache_control: Option<CacheControl>,
    },
    Document {
        source: DocumentSource,
        title: Option<String>,
        context: Option<String>,
        citations: Option<CitationConfig>,
        cache_control: Option<CacheControl>,
    },
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
        cache_control: Option<CacheControl>,
    },
    ToolResult {
        tool_use_id: String,
        content: Option<String>,
        is_error: Option<bool>,
    },
    Thinking {
        thinking: String,
        signature: Option<String>,
    },
    RedactedThinking {
        data: String,
    },
    SearchResult {
        source: String,
        title: String,
        content: Vec<TextBlock>,
        citations: Option<CitationConfig>,
        cache_control: Option<CacheControl>,
    },
}

impl<'de> serde::Deserialize<'de> for ContentBlock {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;

        // Try to deserialize as a known variant via the helper enum
        match serde_json::from_value::<ContentBlockHelper>(value.clone()) {
            Ok(helper) => Ok(match helper {
                ContentBlockHelper::Text {
                    text,
                    cache_control,
                    citations,
                } => ContentBlock::Text {
                    text,
                    cache_control,
                    citations,
                },
                ContentBlockHelper::Image {
                    source,
                    cache_control,
                } => ContentBlock::Image {
                    source,
                    cache_control,
                },
                ContentBlockHelper::Document {
                    source,
                    title,
                    context,
                    citations,
                    cache_control,
                } => ContentBlock::Document {
                    source,
                    title,
                    context,
                    citations,
                    cache_control,
                },
                ContentBlockHelper::ToolUse {
                    id,
                    name,
                    input,
                    cache_control,
                } => ContentBlock::ToolUse {
                    id,
                    name,
                    input,
                    cache_control,
                },
                ContentBlockHelper::ToolResult {
                    tool_use_id,
                    content,
                    is_error,
                } => ContentBlock::ToolResult {
                    tool_use_id,
                    content,
                    is_error,
                },
                ContentBlockHelper::Thinking {
                    thinking,
                    signature,
                } => ContentBlock::Thinking {
                    thinking,
                    signature,
                },
                ContentBlockHelper::RedactedThinking { data } => {
                    ContentBlock::RedactedThinking { data }
                }
                ContentBlockHelper::SearchResult {
                    source,
                    title,
                    content,
                    citations,
                    cache_control,
                } => ContentBlock::SearchResult {
                    source,
                    title,
                    content,
                    citations,
                    cache_control,
                },
            }),
            Err(_) => {
                // Unknown type -- extract the type field and capture the raw data
                let block_type = value
                    .get("type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("unknown")
                    .to_string();
                Ok(ContentBlock::Unknown {
                    block_type,
                    data: value,
                })
            }
        }
    }
}

/// Text block for search result content
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextBlock {
    #[serde(rename = "type")]
    pub block_type: String, // Always "text"
    pub text: String,
}

/// Image source for vision
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ImageSource {
    /// Base64-encoded image
    Base64 { media_type: String, data: String },
    /// Image URL
    Url { url: String },
    /// File ID from Files API
    ///
    /// Requires beta header: `anthropic-beta: files-api-2025-04-14`
    File { file_id: String },
}

/// Document source
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DocumentSource {
    /// File ID from Files API
    File { file_id: String },
    /// Inline text document
    Text { media_type: String, data: String },
}

/// Citation configuration for documents and search results
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CitationConfig {
    pub enabled: bool,
}

/// Citation location in a response
///
/// Claude automatically includes these when using search_result blocks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Citation {
    #[serde(rename = "type")]
    pub citation_type: String, // "search_result_location"

    pub source: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    pub cited_text: String,

    pub search_result_index: usize,

    pub start_block_index: usize,

    pub end_block_index: usize,
}

/// Cache control for prompt caching
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CacheControl {
    #[serde(rename = "type")]
    pub cache_type: CacheType,

    /// TTL for cached content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<CacheTtl>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum CacheType {
    Ephemeral,
}

/// Cache TTL duration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CacheTtl {
    /// 5-minute TTL (default)
    #[serde(rename = "5m")]
    FiveMinutes,
    /// 1-hour TTL
    #[serde(rename = "1h")]
    OneHour,
}

impl CacheControl {
    /// Create an ephemeral cache control
    pub fn ephemeral() -> Self {
        Self {
            cache_type: CacheType::Ephemeral,
            ttl: None,
        }
    }

    /// Create an ephemeral cache control with a specific TTL
    pub fn ephemeral_with_ttl(ttl: CacheTtl) -> Self {
        Self {
            cache_type: CacheType::Ephemeral,
            ttl: Some(ttl),
        }
    }
}

/// A message in the conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub role: Role,
    pub content: Vec<ContentBlock>,
}

impl Message {
    /// Create a user message with text content
    pub fn user(text: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            content: vec![ContentBlock::Text {
                text: text.into(),
                cache_control: None,
                citations: None,
            }],
        }
    }

    /// Create an assistant message with text content
    pub fn assistant(text: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            content: vec![ContentBlock::Text {
                text: text.into(),
                cache_control: None,
                citations: None,
            }],
        }
    }

    /// Create a user message with a tool result
    pub fn tool_result(tool_use_id: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            content: vec![ContentBlock::ToolResult {
                tool_use_id: tool_use_id.into(),
                content: Some(content.into()),
                is_error: None,
            }],
        }
    }
}

/// System prompt format
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SystemPrompt {
    String(String),
    Blocks(Vec<SystemBlock>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemBlock {
    #[serde(rename = "type")]
    pub block_type: String,
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControl>,
}

/// Tool definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tool {
    pub name: String,
    pub description: String,
    pub input_schema: serde_json::Value,

    /// If true, Claude will use this tool programmatically without asking the user
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_user_input: Option<bool>,

    /// Example inputs for the tool (beta feature)
    ///
    /// Requires beta header: `anthropic-beta: advanced-tool-use-2025-11-20`
    /// Each example must be valid according to the input_schema.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_examples: Option<Vec<serde_json::Value>>,

    /// Cache control for this tool definition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControl>,
}

/// Tool choice configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ToolChoice {
    /// Let Claude decide whether to use tools (default)
    Auto,
    /// Claude must use one of the provided tools
    Any,
    /// Force Claude to use a specific tool
    Tool { name: String },
    /// Prevent Claude from using any tools
    None,
}

impl ToolChoice {
    /// Create Auto variant
    pub fn auto() -> Self {
        Self::Auto
    }

    /// Create Any variant
    pub fn any() -> Self {
        Self::Any
    }

    /// Create Tool variant with specific tool name
    pub fn tool(name: impl Into<String>) -> Self {
        Self::Tool { name: name.into() }
    }

    /// Create None variant
    pub fn none() -> Self {
        Self::None
    }
}

/// Detailed output token breakdown
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct OutputTokensDetails {
    /// Tokens used for thinking
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_tokens: Option<u32>,
}

/// Server tool usage counts
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct ServerToolUsage {
    /// Number of web search requests made
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_search_requests: Option<u32>,
    /// Number of web fetch requests made
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_fetch_requests: Option<u32>,
}

/// Token usage information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    pub input_tokens: u32,
    pub output_tokens: u32,

    /// Tokens written to cache (prompt caching)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_creation_input_tokens: Option<u32>,

    /// Tokens read from cache (prompt caching)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_read_input_tokens: Option<u32>,

    /// Detailed breakdown of output tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_tokens_details: Option<OutputTokensDetails>,

    /// Server tool invocation counts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_tool_use: Option<ServerToolUsage>,

    /// Which service tier handled this request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<String>,

    /// Which geographic region processed this request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inference_geo: Option<String>,
}

/// Extended usage information for responses with thinking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtendedUsage {
    #[serde(flatten)]
    pub base: Usage,

    /// Tokens used for thinking (extended thinking)
    ///
    /// Note: With summarized thinking (Claude 4+), you're billed for the full
    /// thinking tokens, not the summarized tokens you see in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_tokens: Option<u32>,
}

/// Request to create a message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessagesRequest {
    /// Model identifier (e.g., "claude-3-5-sonnet-20241022")
    pub model: String,

    /// Maximum tokens to generate
    pub max_tokens: u32,

    /// Conversation messages
    pub messages: Vec<Message>,

    /// System prompt
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<SystemPrompt>,

    /// Available tools
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<Tool>>,

    /// Tool choice configuration
    ///
    /// Controls how Claude uses tools:
    /// - `Auto` (default): Claude decides whether to use tools
    /// - `Any`: Claude must use one of the provided tools
    /// - `Tool { name }`: Force Claude to use a specific tool
    /// - `None`: Prevent Claude from using any tools
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,

    /// Disable parallel tool use
    ///
    /// When true with `tool_choice: auto`, Claude will use at most one tool.
    /// When true with `tool_choice: any/tool`, Claude will use exactly one tool.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_parallel_tool_use: Option<bool>,

    /// Sampling temperature (0.0 to 1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Top-p sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,

    /// Top-k sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,

    /// Stop sequences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,

    /// Whether to stream the response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,

    /// Output configuration (beta)
    ///
    /// Controls output behavior like effort level.
    /// Requires beta header for effort: `anthropic-beta: effort-2025-11-24`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_config: Option<OutputConfig>,

    /// Extended thinking configuration
    ///
    /// Enables Claude's step-by-step reasoning process.
    /// Supported models: Sonnet 4.5, Haiku 4.5, Opus 4.5, and more.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<ThinkingConfig>,

    /// Request metadata for abuse detection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,

    /// Service tier for request routing
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<ServiceTier>,

    /// Geographic inference routing
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inference_geo: Option<String>,
}

/// Extended thinking configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ThinkingConfig {
    /// Enable extended thinking with token budget
    Enabled {
        /// Maximum tokens Claude can use for thinking
        ///
        /// Minimum: 1024 tokens
        /// Can exceed max_tokens with interleaved thinking (beta: interleaved-thinking-2025-05-14)
        budget_tokens: u32,
    },
    /// Disable extended thinking
    Disabled,
}

/// Output configuration for controlling response behavior
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OutputConfig {
    /// Effort level: controls token spending vs. response quality
    ///
    /// - `high` (default): Maximum capability, uses as many tokens as needed
    /// - `medium`: Balanced approach with moderate token savings
    /// - `low`: Most efficient, significant token savings
    ///
    /// Requires beta header: `anthropic-beta: effort-2025-11-24`
    /// Only supported by Claude Opus 4.5
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effort: Option<EffortLevel>,
}

/// Effort level for response generation
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum EffortLevel {
    /// Maximum capability (default if omitted)
    High,
    /// Balanced token savings
    Medium,
    /// Maximum token efficiency
    Low,
    /// Extra-high effort
    #[serde(rename = "xhigh")]
    XHigh,
    /// Maximum effort
    Max,
}

/// Request metadata for abuse detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metadata {
    /// Opaque user identifier (uuid or hash, no PII)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
}

/// Service tier for request routing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceTier {
    Auto,
    StandardOnly,
}

impl MessagesRequest {
    /// Create a new message request with required fields
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message};
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-3-5-sonnet-20241022",
    ///     1024,
    ///     vec![Message::user("Hello!")]
    /// );
    /// ```
    pub fn new(model: impl Into<String>, max_tokens: u32, messages: Vec<Message>) -> Self {
        Self {
            model: model.into(),
            max_tokens,
            messages,
            system: None,
            tools: None,
            tool_choice: None,
            disable_parallel_tool_use: None,
            temperature: None,
            top_p: None,
            top_k: None,
            stop_sequences: None,
            stream: None,
            output_config: None,
            thinking: None,
            metadata: None,
            service_tier: None,
            inference_geo: None,
        }
    }

    /// Set the system prompt.
    ///
    /// The system prompt provides instructions and context that guide Claude's behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message};
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("What's 2+2?")],
    /// )
    /// .with_system("You are a math tutor. Always explain your reasoning step by step.");
    /// ```
    pub fn with_system(mut self, system: impl Into<String>) -> Self {
        self.system = Some(SystemPrompt::String(system.into()));
        self
    }

    /// Set the available tools for this request.
    ///
    /// Tools allow Claude to call functions and return structured data.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message, Tool};
    /// use serde_json::json;
    ///
    /// let calculator = Tool {
    ///     name: "calculator".into(),
    ///     description: "Perform basic arithmetic operations".into(),
    ///     input_schema: json!({
    ///         "type": "object",
    ///         "properties": {
    ///             "operation": { "type": "string", "enum": ["add", "subtract", "multiply", "divide"] },
    ///             "a": { "type": "number" },
    ///             "b": { "type": "number" }
    ///         },
    ///         "required": ["operation", "a", "b"]
    ///     }),
    ///     disable_user_input: Some(true),
    ///     input_examples: None,
    ///     cache_control: None,
    /// };
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("What's 15 * 7?")],
    /// )
    /// .with_tools(vec![calculator]);
    /// ```
    pub fn with_tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Set tool choice configuration.
    ///
    /// Controls how Claude decides whether and which tools to use.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message, ToolChoice};
    ///
    /// // Force Claude to use a specific tool
    /// let request = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("Search for weather")],
    /// )
    /// .with_tool_choice(ToolChoice::tool("get_weather"));
    ///
    /// // Or let Claude decide (default)
    /// let request2 = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("Hello")],
    /// )
    /// .with_tool_choice(ToolChoice::auto());
    /// ```
    pub fn with_tool_choice(mut self, choice: ToolChoice) -> Self {
        self.tool_choice = Some(choice);
        self
    }

    /// Disable parallel tool use.
    ///
    /// When enabled, Claude will only use one tool at a time instead of
    /// potentially calling multiple tools in parallel.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message};
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("Get weather and stock price")],
    /// )
    /// .with_disable_parallel_tool_use(true);  // Forces sequential tool calls
    /// ```
    pub fn with_disable_parallel_tool_use(mut self, disable: bool) -> Self {
        self.disable_parallel_tool_use = Some(disable);
        self
    }

    /// Set the sampling temperature.
    ///
    /// Temperature controls randomness in the output:
    /// - `0.0` - Deterministic, most likely tokens
    /// - `0.5` - Balanced creativity
    /// - `1.0` - Maximum randomness
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message};
    ///
    /// // Low temperature for factual responses
    /// let factual = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("What is the capital of France?")],
    /// )
    /// .with_temperature(0.0);
    ///
    /// // Higher temperature for creative writing
    /// let creative = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     1024,
    ///     vec![Message::user("Write a short poem about the ocean.")],
    /// )
    /// .with_temperature(0.8);
    /// ```
    pub fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Set effort level (beta - requires `anthropic-beta: effort-2025-11-24` header).
    ///
    /// Controls the trade-off between response quality and token usage.
    /// Only supported by Claude Opus 4.5.
    ///
    /// # Effort Levels
    ///
    /// - [`EffortLevel::High`] - Maximum capability (default)
    /// - [`EffortLevel::Medium`] - Balanced token savings
    /// - [`EffortLevel::Low`] - Maximum efficiency
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message, EffortLevel};
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-opus-4-5-20251101",  // Opus 4.5 only
    ///     1024,
    ///     vec![Message::user("Summarize this document briefly.")],
    /// )
    /// .with_effort(EffortLevel::Low);  // Optimize for efficiency
    /// ```
    pub fn with_effort(mut self, effort: EffortLevel) -> Self {
        self.output_config = Some(OutputConfig {
            effort: Some(effort),
        });
        self
    }

    /// Enable extended thinking with a token budget.
    ///
    /// Extended thinking allows Claude to reason through complex problems
    /// step-by-step before providing a final answer.
    ///
    /// # Requirements
    ///
    /// - Supported by: Claude Sonnet 4.5, Haiku 4.5, Opus 4.5, and other Claude 4+ models
    /// - Minimum budget: 1024 tokens
    /// - The thinking process appears in [`ContentBlock::Thinking`] blocks
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{MessagesRequest, Message};
    ///
    /// let request = MessagesRequest::new(
    ///     "claude-sonnet-4-5-20250929",
    ///     8192,
    ///     vec![Message::user("Solve this step by step: If a train travels...")],
    /// )
    /// .with_thinking(4096);  // Allow up to 4096 tokens for reasoning
    /// ```
    pub fn with_thinking(mut self, budget_tokens: u32) -> Self {
        self.thinking = Some(ThinkingConfig::Enabled { budget_tokens });
        self
    }

    /// Set request metadata for abuse detection.
    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Set the service tier for request routing.
    pub fn with_service_tier(mut self, tier: ServiceTier) -> Self {
        self.service_tier = Some(tier);
        self
    }

    /// Set the geographic inference routing.
    pub fn with_inference_geo(mut self, geo: impl Into<String>) -> Self {
        self.inference_geo = Some(geo.into());
        self
    }
}

/// Stop reason for a message
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    /// Natural end of message
    EndTurn,
    /// Hit max tokens
    MaxTokens,
    /// Hit a stop sequence
    StopSequence,
    /// Model wants to use a tool
    ToolUse,
    /// Long-running server tool paused the turn
    ///
    /// Continue by sending the response content back in the next request.
    /// Used with server tools like web search.
    PauseTurn,
    /// Model refused the request
    Refusal,
}

/// Details about why the model stopped (currently only for refusals)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StopDetails {
    #[serde(rename = "type")]
    pub stop_type: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<RefusalCategory>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub explanation: Option<String>,
}

/// Category of content refusal
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RefusalCategory {
    Cyber,
    Bio,
    ReasoningExtraction,
}

/// Response from creating a message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessagesResponse {
    pub id: String,

    #[serde(rename = "type")]
    pub response_type: String,

    pub role: Role,

    pub content: Vec<ContentBlock>,

    pub model: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<StopReason>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequence: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_details: Option<StopDetails>,

    pub usage: Usage,

    /// Rate limit info from response headers (not part of JSON body)
    #[serde(skip)]
    pub rate_limit_info: Option<RateLimitInfo>,
}

/// Rate limit information from API response headers
///
/// The API returns these headers with every response to help
/// clients manage their request rate.
#[derive(Debug, Clone, Default)]
pub struct RateLimitInfo {
    /// Remaining requests in current window
    pub requests_remaining: Option<u32>,
    /// Remaining tokens in current window
    pub tokens_remaining: Option<u32>,
    /// Time until request limit resets (ISO 8601)
    pub requests_reset: Option<String>,
    /// Time until token limit resets (ISO 8601)
    pub tokens_reset: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_control_ephemeral() {
        let cache = CacheControl::ephemeral();
        assert_eq!(cache.cache_type, CacheType::Ephemeral);
    }

    #[test]
    fn test_cache_control_serialization() {
        let cache = CacheControl::ephemeral();
        let json = serde_json::to_string(&cache).unwrap();
        assert_eq!(json, r#"{"type":"ephemeral"}"#);
    }

    #[test]
    fn test_text_content_with_cache() {
        let content = ContentBlock::Text {
            text: "test".into(),
            cache_control: Some(CacheControl::ephemeral()),
            citations: None,
        };

        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "test");
        assert_eq!(json["cache_control"]["type"], "ephemeral");
    }

    #[test]
    fn test_system_block_with_cache() {
        let block = SystemBlock {
            block_type: "text".into(),
            text: "You are helpful".into(),
            cache_control: Some(CacheControl::ephemeral()),
        };

        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["cache_control"]["type"], "ephemeral");
    }

    #[test]
    fn test_tool_with_cache() {
        let tool = Tool {
            name: "test".into(),
            description: "test tool".into(),
            input_schema: serde_json::json!({"type": "object"}),
            disable_user_input: Some(true),
            input_examples: None,
            cache_control: Some(CacheControl::ephemeral()),
        };

        let json = serde_json::to_value(&tool).unwrap();
        assert_eq!(json["name"], "test");
        assert_eq!(json["cache_control"]["type"], "ephemeral");
    }

    #[test]
    fn test_message_constructors() {
        let user_msg = Message::user("hello");
        assert_eq!(user_msg.role, Role::User);
        assert_eq!(user_msg.content.len(), 1);

        let assistant_msg = Message::assistant("hi");
        assert_eq!(assistant_msg.role, Role::Assistant);

        let tool_result = Message::tool_result("id_123", "result");
        assert_eq!(tool_result.role, Role::User);
        match &tool_result.content[0] {
            ContentBlock::ToolResult { tool_use_id, .. } => {
                assert_eq!(tool_use_id, "id_123");
            }
            _ => panic!("Expected ToolResult"),
        }
    }

    #[test]
    fn test_messages_request_builder() {
        let request = MessagesRequest::new(
            "claude-sonnet-4-5-20250929",
            1024,
            vec![Message::user("test")],
        )
        .with_system("System prompt")
        .with_temperature(0.7);

        assert_eq!(request.model, "claude-sonnet-4-5-20250929");
        assert_eq!(request.max_tokens, 1024);
        assert_eq!(request.messages.len(), 1);
        assert!(request.system.is_some());
        assert_eq!(request.temperature, Some(0.7));
    }

    #[test]
    fn test_metadata_serialization() {
        let request = MessagesRequest::new(
            "claude-sonnet-4-5-20250929",
            1024,
            vec![Message::user("Hello")],
        )
        .with_metadata(Metadata {
            user_id: Some("user-abc-123".into()),
        });

        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["metadata"]["user_id"], "user-abc-123");
    }

    #[test]
    fn test_service_tier_serialization() {
        let json = serde_json::to_string(&ServiceTier::StandardOnly).unwrap();
        assert_eq!(json, r#""standard_only""#);

        let json = serde_json::to_string(&ServiceTier::Auto).unwrap();
        assert_eq!(json, r#""auto""#);
    }

    #[test]
    fn test_refusal_stop_reason_deserialization() {
        let json = r#"{
            "id": "msg_123",
            "type": "message",
            "role": "assistant",
            "content": [],
            "model": "claude-sonnet-4-5-20250929",
            "stop_reason": "refusal",
            "stop_details": {
                "type": "refusal",
                "category": "cyber",
                "explanation": "Request involves prohibited content"
            },
            "usage": { "input_tokens": 10, "output_tokens": 0 }
        }"#;

        let response: MessagesResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.stop_reason, Some(StopReason::Refusal));
        let details = response.stop_details.as_ref().unwrap();
        assert_eq!(details.category, Some(RefusalCategory::Cyber));
        assert_eq!(
            details.explanation.as_deref(),
            Some("Request involves prohibited content")
        );
    }

    #[test]
    fn test_effort_xhigh_and_max() {
        let json_xhigh = serde_json::to_string(&EffortLevel::XHigh).unwrap();
        assert_eq!(json_xhigh, r#""xhigh""#);

        let json_max = serde_json::to_string(&EffortLevel::Max).unwrap();
        assert_eq!(json_max, r#""max""#);

        // Round-trip
        let parsed: EffortLevel = serde_json::from_str(r#""xhigh""#).unwrap();
        assert_eq!(parsed, EffortLevel::XHigh);

        let parsed: EffortLevel = serde_json::from_str(r#""max""#).unwrap();
        assert_eq!(parsed, EffortLevel::Max);
    }

    // Task 5: CacheTtl tests

    #[test]
    fn test_cache_control_with_ttl() {
        let cache = CacheControl::ephemeral_with_ttl(CacheTtl::OneHour);
        let json = serde_json::to_value(&cache).unwrap();
        assert_eq!(json["type"], "ephemeral");
        assert_eq!(json["ttl"], "1h");
    }

    #[test]
    fn test_cache_control_ttl_deserialization() {
        let json = r#"{"type": "ephemeral", "ttl": "5m"}"#;
        let cache: CacheControl = serde_json::from_str(json).unwrap();
        assert_eq!(cache.ttl, Some(CacheTtl::FiveMinutes));
    }

    #[test]
    fn test_cache_control_without_ttl_still_works() {
        // Existing behavior: no ttl field
        let cache = CacheControl::ephemeral();
        let json = serde_json::to_string(&cache).unwrap();
        assert_eq!(json, r#"{"type":"ephemeral"}"#);
        assert_eq!(cache.ttl, None);
    }

    // Task 6: Usage expansion tests

    #[test]
    fn test_usage_with_details_deserialization() {
        let json = r#"{
            "input_tokens": 100,
            "output_tokens": 50,
            "cache_creation_input_tokens": 10,
            "cache_read_input_tokens": 5,
            "output_tokens_details": {
                "thinking_tokens": 20
            },
            "server_tool_use": {
                "web_search_requests": 3
            },
            "service_tier": "priority",
            "inference_geo": "us"
        }"#;

        let usage: Usage = serde_json::from_str(json).unwrap();
        assert_eq!(usage.input_tokens, 100);
        assert_eq!(usage.output_tokens, 50);
        let details = usage.output_tokens_details.unwrap();
        assert_eq!(details.thinking_tokens, Some(20));
        let server = usage.server_tool_use.unwrap();
        assert_eq!(server.web_search_requests, Some(3));
        assert_eq!(usage.service_tier.as_deref(), Some("priority"));
    }

    #[test]
    fn test_usage_without_new_fields_still_works() {
        let json = r#"{"input_tokens": 10, "output_tokens": 5}"#;
        let usage: Usage = serde_json::from_str(json).unwrap();
        assert_eq!(usage.input_tokens, 10);
        assert!(usage.output_tokens_details.is_none());
        assert!(usage.server_tool_use.is_none());
    }

    // Task 8: RateLimitInfo tests

    #[test]
    fn test_rate_limit_info_default() {
        let info = RateLimitInfo::default();
        assert!(info.requests_remaining.is_none());
        assert!(info.tokens_remaining.is_none());
        assert!(info.requests_reset.is_none());
        assert!(info.tokens_reset.is_none());
    }

    #[test]
    fn test_response_deserialization_with_skipped_rate_limit() {
        let json = r#"{
            "id": "msg_123",
            "type": "message",
            "role": "assistant",
            "content": [{"type": "text", "text": "hello"}],
            "model": "claude-sonnet-4-5-20250929",
            "stop_reason": "end_turn",
            "usage": {"input_tokens": 10, "output_tokens": 5}
        }"#;

        let response: MessagesResponse = serde_json::from_str(json).unwrap();
        assert!(response.rate_limit_info.is_none()); // Skipped in JSON
    }

    // Task 7: ContentBlock::Unknown forward-compatible deserialization tests

    #[test]
    fn test_unknown_content_block_deserializes() {
        let json =
            r#"{"type": "server_tool_use", "id": "stu_123", "name": "web_search", "input": {}}"#;
        let block: ContentBlock = serde_json::from_str(json).unwrap();
        match block {
            ContentBlock::Unknown { block_type, data } => {
                assert_eq!(block_type, "server_tool_use");
                assert_eq!(data["name"], "web_search");
                assert_eq!(data["id"], "stu_123");
            }
            _ => panic!("Expected Unknown variant"),
        }
    }

    #[test]
    fn test_known_content_blocks_still_work() {
        let json = r#"{"type": "text", "text": "hello"}"#;
        let block: ContentBlock = serde_json::from_str(json).unwrap();
        match block {
            ContentBlock::Text { text, .. } => assert_eq!(text, "hello"),
            _ => panic!("Expected Text variant"),
        }
    }

    #[test]
    fn test_content_block_roundtrip() {
        let original = ContentBlock::Text {
            text: "test".into(),
            cache_control: None,
            citations: None,
        };
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: ContentBlock = serde_json::from_str(&json).unwrap();
        match deserialized {
            ContentBlock::Text { text, .. } => assert_eq!(text, "test"),
            _ => panic!("Expected Text variant after roundtrip"),
        }
    }

    #[test]
    fn test_unknown_block_in_response() {
        let json = r#"{
            "id": "msg_123",
            "type": "message",
            "role": "assistant",
            "content": [
                {"type": "text", "text": "hello"},
                {"type": "server_tool_use", "id": "stu_1", "name": "web_search", "input": {}}
            ],
            "model": "claude-sonnet-4-5-20250929",
            "stop_reason": "end_turn",
            "usage": {"input_tokens": 10, "output_tokens": 5}
        }"#;

        let response: MessagesResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.content.len(), 2);
        match &response.content[0] {
            ContentBlock::Text { text, .. } => assert_eq!(text, "hello"),
            _ => panic!("Expected Text variant"),
        }
        match &response.content[1] {
            ContentBlock::Unknown { block_type, .. } => {
                assert_eq!(block_type, "server_tool_use");
            }
            _ => panic!("Expected Unknown variant"),
        }
    }

    #[test]
    fn test_unknown_block_without_type_field() {
        // Edge case: a JSON object with no "type" field should fail for the helper
        // and fall through to Unknown with "unknown" as block_type
        let json = r#"{"foo": "bar"}"#;
        let block: ContentBlock = serde_json::from_str(json).unwrap();
        match block {
            ContentBlock::Unknown { block_type, data } => {
                assert_eq!(block_type, "unknown");
                assert_eq!(data["foo"], "bar");
            }
            _ => panic!("Expected Unknown variant"),
        }
    }
}