mixtape-core 0.4.0

An agentic AI framework for Rust
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
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Image formats supported for tool results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageFormat {
    Png,
    Jpeg,
    Gif,
    Webp,
}

/// Document formats supported for tool results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DocumentFormat {
    Pdf,
    Csv,
    Doc,
    Docx,
    Html,
    Md,
    Txt,
    Xls,
    Xlsx,
}

/// Result types that tools can return.
///
/// Tools can return different content types depending on their purpose.
/// All providers support Text and Json. Image and Document support varies by provider
/// (Bedrock supports all types; future providers may fall back to text descriptions).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ToolResult {
    /// Plain text response
    Text(String),

    /// Structured JSON data - use for complex responses
    Json(Value),

    /// Image data - supported by Bedrock (Claude, Nova models)
    Image {
        format: ImageFormat,
        /// Raw image bytes (not base64 encoded)
        data: Vec<u8>,
    },

    /// Document data - supported by Bedrock (Claude, Nova models)
    Document {
        format: DocumentFormat,
        /// Raw document bytes
        data: Vec<u8>,
        /// Optional document name/filename
        name: Option<String>,
    },
}

impl ToolResult {
    /// Create a JSON result from any serializable type
    pub fn json<T: Serialize>(value: T) -> Result<Self, serde_json::Error> {
        Ok(Self::Json(serde_json::to_value(value)?))
    }

    /// Create a text result from a string
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text(s.into())
    }

    /// Create an image result from raw bytes
    pub fn image(format: ImageFormat, data: Vec<u8>) -> Self {
        Self::Image { format, data }
    }

    /// Create a document result from raw bytes
    pub fn document(format: DocumentFormat, data: Vec<u8>) -> Self {
        Self::Document {
            format,
            data,
            name: None,
        }
    }

    /// Create a document result with a filename
    pub fn document_with_name(
        format: DocumentFormat,
        data: Vec<u8>,
        name: impl Into<String>,
    ) -> Self {
        Self::Document {
            format,
            data,
            name: Some(name.into()),
        }
    }

    /// Get the text content if this is a Text variant, or convert to string description
    pub fn as_text(&self) -> String {
        match self {
            ToolResult::Text(s) => s.clone(),
            ToolResult::Json(v) => v.to_string(),
            ToolResult::Image { format, data } => {
                format!("[Image: {:?}, {} bytes]", format, data.len())
            }
            ToolResult::Document { format, data, name } => {
                let name_str = name.as_deref().unwrap_or("unnamed");
                format!(
                    "[Document: {:?}, {}, {} bytes]",
                    format,
                    name_str,
                    data.len()
                )
            }
        }
    }

    /// Get a reference to the text content if this is a Text variant
    pub fn as_str(&self) -> Option<&str> {
        match self {
            ToolResult::Text(s) => Some(s),
            _ => None,
        }
    }
}

/// Convert strings directly to ToolResult::Text
impl From<String> for ToolResult {
    fn from(s: String) -> Self {
        Self::Text(s)
    }
}

impl From<&str> for ToolResult {
    fn from(s: &str) -> Self {
        Self::Text(s.to_string())
    }
}

/// Errors that can occur during tool execution
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("Path validation failed: {0}")]
    PathValidation(String),

    #[error("{0}")]
    Custom(String),
}

impl From<String> for ToolError {
    fn from(s: String) -> Self {
        Self::Custom(s)
    }
}

impl From<&str> for ToolError {
    fn from(s: &str) -> Self {
        Self::Custom(s.to_string())
    }
}

/// Trait for implementing tools that can be used by AI agents.
///
/// Tools define an input type with `#[derive(Deserialize, JsonSchema)]` to automatically
/// generate JSON schemas from Rust types, providing excellent developer experience.
///
/// # Async Tools Example
///
/// ```rust
/// use mixtape_core::{Tool, ToolResult, ToolError};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
/// use std::time::Duration;
///
/// #[derive(Deserialize, JsonSchema)]
/// struct DelayInput {
///     /// Duration in milliseconds
///     ms: u64,
/// }
///
/// struct DelayTool;
///
/// impl Tool for DelayTool {
///     type Input = DelayInput;
///
///     fn name(&self) -> &str { "delay" }
///     fn description(&self) -> &str { "Wait for a duration" }
///
///     fn execute(&self, input: Self::Input) -> impl std::future::Future<Output = Result<ToolResult, ToolError>> + Send {
///         async move {
///             // Async operations work naturally
///             tokio::time::sleep(Duration::from_millis(input.ms)).await;
///             Ok(format!("Waited {}ms", input.ms).into())  // Converts to ToolResult::Text
///         }
///     }
/// }
/// ```
///
/// # Returning JSON Data
///
/// Tools can return structured JSON data:
///
/// ```rust
/// use mixtape_core::{Tool, ToolResult, ToolError};
/// use schemars::JsonSchema;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, JsonSchema)]
/// struct CalculateInput {
///     a: i32,
///     b: i32,
/// }
///
/// #[derive(Serialize)]
/// struct CalculateOutput {
///     sum: i32,
///     product: i32,
/// }
///
/// struct CalculateTool;
///
/// impl Tool for CalculateTool {
///     type Input = CalculateInput;
///
///     fn name(&self) -> &str { "calculate" }
///     fn description(&self) -> &str { "Perform calculations" }
///
///     fn execute(&self, input: Self::Input) -> impl std::future::Future<Output = Result<ToolResult, ToolError>> + Send {
///         async move {
///             let output = CalculateOutput {
///                 sum: input.a + input.b,
///                 product: input.a * input.b,
///             };
///             ToolResult::json(output).map_err(Into::into)
///         }
///     }
/// }
/// ```
pub trait Tool: Send + Sync {
    /// The input type for this tool. Must implement `Deserialize` and `JsonSchema`.
    type Input: DeserializeOwned + JsonSchema;

    /// The name of the tool (e.g., "read_file", "calculator")
    fn name(&self) -> &str;

    /// A description of what the tool does
    fn description(&self) -> &str;

    /// Execute the tool with typed input
    fn execute(
        &self,
        input: Self::Input,
    ) -> impl std::future::Future<Output = Result<ToolResult, ToolError>> + Send;

    /// Get the JSON schema for this tool's input.
    ///
    /// This is automatically implemented using the `JsonSchema` derive on `Input`.
    /// The schema is generated at runtime from the type definition.
    fn input_schema(&self) -> Value {
        let schema = schemars::schema_for!(Self::Input);
        serde_json::to_value(schema).expect("Failed to serialize schema")
    }

    // ========================================================================
    // Formatting methods - override these for custom tool presentation
    // ========================================================================

    /// Format tool input as plain text (for JIRA, logs, copy/paste).
    ///
    /// Default implementation shows tool name and parameters with truncation.
    fn format_input_plain(&self, params: &Value) -> String {
        format_params_plain(self.name(), params)
    }

    /// Format tool input with ANSI colors (for terminal display).
    ///
    /// Default implementation shows tool name (bold) and parameters with colors.
    fn format_input_ansi(&self, params: &Value) -> String {
        format_params_ansi(self.name(), params)
    }

    /// Format tool input as Markdown (for docs, GitHub, rendered UIs).
    ///
    /// Default implementation shows tool name and parameters in markdown format.
    fn format_input_markdown(&self, params: &Value) -> String {
        format_params_markdown(self.name(), params)
    }

    /// Format tool output as plain text.
    ///
    /// Default implementation shows result text with truncation.
    fn format_output_plain(&self, result: &ToolResult) -> String {
        format_result_plain(result)
    }

    /// Format tool output with ANSI colors.
    ///
    /// Default implementation shows result with success indicator and truncation.
    fn format_output_ansi(&self, result: &ToolResult) -> String {
        format_result_ansi(result)
    }

    /// Format tool output as Markdown.
    ///
    /// Default implementation shows result in a code block with truncation.
    fn format_output_markdown(&self, result: &ToolResult) -> String {
        format_result_markdown(result)
    }
}

/// Object-safe trait for dynamic tool dispatch (used internally by the agent).
///
/// Users should implement `Tool` instead and use `box_tool()` to convert.
pub trait DynTool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn input_schema(&self) -> Value;
    fn execute_raw(
        &self,
        input: Value,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<ToolResult, ToolError>> + Send + '_>,
    >;

    // Formatting methods
    fn format_input_plain(&self, params: &Value) -> String;
    fn format_input_ansi(&self, params: &Value) -> String;
    fn format_input_markdown(&self, params: &Value) -> String;
    fn format_output_plain(&self, result: &ToolResult) -> String;
    fn format_output_ansi(&self, result: &ToolResult) -> String;
    fn format_output_markdown(&self, result: &ToolResult) -> String;
}

/// Convert a `Tool` into a type-erased `Box<dyn DynTool>` for storage in collections.
pub fn box_tool<T: Tool + 'static>(tool: T) -> Box<dyn DynTool> {
    Box::new(ToolWrapper(tool))
}

/// Create a `Vec<Box<dyn DynTool>>` from heterogeneous tool types.
///
/// This macro boxes each tool and collects them into a vector that can be
/// passed to [`crate::AgentBuilder::add_tools()`].
///
/// # Example
///
/// ```ignore
/// use mixtape_core::{Agent, box_tools, ClaudeSonnet4};
///
/// let agent = Agent::builder()
///     .bedrock(ClaudeSonnet4)
///     .add_tools(box_tools![Calculator, WeatherLookup, FileReader])
///     .build()
///     .await?;
/// ```
///
/// This is equivalent to:
///
/// ```ignore
/// .add_tool(Calculator)
/// .add_tool(WeatherLookup)
/// .add_tool(FileReader)
/// ```
#[macro_export]
macro_rules! box_tools {
    ($($tool:expr),* $(,)?) => {
        vec![$($crate::tool::box_tool($tool)),*]
    };
}

/// Internal wrapper that implements DynTool for any Tool
struct ToolWrapper<T>(T);

impl<T: Tool + 'static> DynTool for ToolWrapper<T> {
    fn name(&self) -> &str {
        self.0.name()
    }

    fn description(&self) -> &str {
        self.0.description()
    }

    fn input_schema(&self) -> Value {
        self.0.input_schema()
    }

    fn execute_raw(
        &self,
        input: Value,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<ToolResult, ToolError>> + Send + '_>,
    > {
        Box::pin(async move {
            let typed_input: T::Input = serde_json::from_value(input)
                .map_err(|e| ToolError::Custom(format!("Failed to deserialize input: {}", e)))?;

            self.0.execute(typed_input).await
        })
    }

    fn format_input_plain(&self, params: &Value) -> String {
        self.0.format_input_plain(params)
    }

    fn format_input_ansi(&self, params: &Value) -> String {
        self.0.format_input_ansi(params)
    }

    fn format_input_markdown(&self, params: &Value) -> String {
        self.0.format_input_markdown(params)
    }

    fn format_output_plain(&self, result: &ToolResult) -> String {
        self.0.format_output_plain(result)
    }

    fn format_output_ansi(&self, result: &ToolResult) -> String {
        self.0.format_output_ansi(result)
    }

    fn format_output_markdown(&self, result: &ToolResult) -> String {
        self.0.format_output_markdown(result)
    }
}

// ============================================================================
// Default formatting helpers
// ============================================================================

const MAX_PARAMS: usize = 10;
const MAX_VALUE_LEN: usize = 80;
const MAX_OUTPUT_LINES: usize = 12;

/// Format a JSON value for display, with truncation
fn format_value_preview(value: &Value) -> String {
    match value {
        Value::String(s) => {
            if s.len() > MAX_VALUE_LEN {
                format!("\"{}…\"", &s[..MAX_VALUE_LEN])
            } else {
                format!("\"{}\"", s)
            }
        }
        Value::Array(arr) => format!("[{} items]", arr.len()),
        Value::Object(obj) => format!("{{{} keys}}", obj.len()),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
    }
}

/// Format tool parameters as plain text
pub fn format_params_plain(tool_name: &str, params: &Value) -> String {
    let mut output = tool_name.to_string();

    if let Some(obj) = params.as_object() {
        for (key, value) in obj.iter().take(MAX_PARAMS) {
            output.push_str(&format!("\n  {}: {}", key, format_value_preview(value)));
        }
        if obj.len() > MAX_PARAMS {
            output.push_str(&format!("\n  … +{} more", obj.len() - MAX_PARAMS));
        }
    }

    output
}

/// Format tool parameters with ANSI colors
pub fn format_params_ansi(tool_name: &str, params: &Value) -> String {
    // Bold tool name
    let mut output = format!("\x1b[1m{}\x1b[0m", tool_name);

    if let Some(obj) = params.as_object() {
        for (key, value) in obj.iter().take(MAX_PARAMS) {
            // Dim key, normal value
            output.push_str(&format!(
                "\n  \x1b[2m{}:\x1b[0m {}",
                key,
                format_value_preview(value)
            ));
        }
        if obj.len() > MAX_PARAMS {
            output.push_str(&format!(
                "\n  \x1b[2m… +{} more\x1b[0m",
                obj.len() - MAX_PARAMS
            ));
        }
    }

    output
}

/// Format tool parameters as Markdown
pub fn format_params_markdown(tool_name: &str, params: &Value) -> String {
    let mut output = format!("**{}**", tool_name);

    if let Some(obj) = params.as_object() {
        for (key, value) in obj.iter().take(MAX_PARAMS) {
            output.push_str(&format!("\n- `{}`: {}", key, format_value_preview(value)));
        }
        if obj.len() > MAX_PARAMS {
            output.push_str(&format!("\n- *… +{} more*", obj.len() - MAX_PARAMS));
        }
    }

    output
}

/// Get text representation of a ToolResult
fn result_to_text(result: &ToolResult) -> String {
    match result {
        ToolResult::Text(s) => s.clone(),
        ToolResult::Json(v) => format_json_truncated(v),
        ToolResult::Image { format, data } => {
            format!("[Image: {:?}, {} bytes]", format, data.len())
        }
        ToolResult::Document { format, data, name } => {
            let name_str = name.as_deref().unwrap_or("unnamed");
            format!(
                "[Document: {:?}, {}, {} bytes]",
                format,
                name_str,
                data.len()
            )
        }
    }
}

/// Format JSON with truncated string values and limited object keys
fn format_json_truncated(value: &Value) -> String {
    format_json_truncated_inner(value, 0)
}

fn format_json_truncated_inner(value: &Value, depth: usize) -> String {
    let indent = "  ".repeat(depth);
    let child_indent = "  ".repeat(depth + 1);

    match value {
        Value::String(s) => {
            if s.len() > MAX_VALUE_LEN {
                format!("\"{}…\"", &s[..MAX_VALUE_LEN])
            } else {
                format!("\"{}\"", s)
            }
        }
        Value::Array(arr) => {
            if arr.is_empty() {
                "[]".to_string()
            } else if arr.len() > MAX_PARAMS {
                format!("[{} items]", arr.len())
            } else {
                let items: Vec<String> = arr
                    .iter()
                    .take(MAX_PARAMS)
                    .map(|v| {
                        format!(
                            "{}{}",
                            child_indent,
                            format_json_truncated_inner(v, depth + 1)
                        )
                    })
                    .collect();
                format!("[\n{}\n{}]", items.join(",\n"), indent)
            }
        }
        Value::Object(obj) => {
            if obj.is_empty() {
                "{}".to_string()
            } else {
                let mut items: Vec<String> = obj
                    .iter()
                    .take(MAX_PARAMS)
                    .map(|(k, v)| {
                        format!(
                            "{}\"{}\": {}",
                            child_indent,
                            k,
                            format_json_truncated_inner(v, depth + 1)
                        )
                    })
                    .collect();
                if obj.len() > MAX_PARAMS {
                    items.push(format!(
                        "{}… +{} more",
                        child_indent,
                        obj.len() - MAX_PARAMS
                    ));
                }
                format!("{{\n{}\n{}}}", items.join(",\n"), indent)
            }
        }
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
    }
}

/// Truncate text to max lines, returning (truncated_text, remaining_lines)
fn truncate_lines(text: &str, max_lines: usize) -> (String, usize) {
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() <= max_lines {
        (text.to_string(), 0)
    } else {
        let truncated = lines[..max_lines].join("\n");
        (truncated, lines.len() - max_lines)
    }
}

/// Format tool result as plain text
pub fn format_result_plain(result: &ToolResult) -> String {
    let text = result_to_text(result);
    let (truncated, remaining) = truncate_lines(&text, MAX_OUTPUT_LINES);

    if remaining > 0 {
        format!("{}\n… +{} more lines", truncated, remaining)
    } else {
        truncated
    }
}

/// Format tool result with ANSI colors
pub fn format_result_ansi(result: &ToolResult) -> String {
    let text = result_to_text(result);
    let (truncated, remaining) = truncate_lines(&text, MAX_OUTPUT_LINES);

    if remaining > 0 {
        format!(
            "\x1b[32m✓\x1b[0m\n{}\n\x1b[2m… +{} more lines\x1b[0m",
            truncated, remaining
        )
    } else {
        format!("\x1b[32m✓\x1b[0m\n{}", truncated)
    }
}

/// Format tool result as Markdown
pub fn format_result_markdown(result: &ToolResult) -> String {
    let text = result_to_text(result);
    let (truncated, remaining) = truncate_lines(&text, MAX_OUTPUT_LINES);

    let mut output = String::from("```\n");
    output.push_str(&truncated);
    output.push_str("\n```");

    if remaining > 0 {
        output.push_str(&format!("\n*… +{} more lines*", remaining));
    }

    output
}

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

    // ===== format_value_preview tests =====

    #[test]
    fn test_format_value_preview_string_short() {
        let value = serde_json::json!("hello");
        assert_eq!(format_value_preview(&value), "\"hello\"");
    }

    #[test]
    fn test_format_value_preview_string_long() {
        let long_string = "x".repeat(100);
        let value = serde_json::json!(long_string);
        let preview = format_value_preview(&value);

        // Should be truncated to MAX_VALUE_LEN (80) + quotes + ellipsis
        assert!(preview.len() < 100);
        assert!(preview.ends_with("…\""));
    }

    #[test]
    fn test_format_value_preview_array() {
        let value = serde_json::json!([1, 2, 3, 4, 5]);
        assert_eq!(format_value_preview(&value), "[5 items]");
    }

    #[test]
    fn test_format_value_preview_object() {
        let value = serde_json::json!({"a": 1, "b": 2});
        assert_eq!(format_value_preview(&value), "{2 keys}");
    }

    #[test]
    fn test_format_value_preview_null() {
        let value = serde_json::json!(null);
        assert_eq!(format_value_preview(&value), "null");
    }

    #[test]
    fn test_format_value_preview_bool() {
        assert_eq!(format_value_preview(&serde_json::json!(true)), "true");
        assert_eq!(format_value_preview(&serde_json::json!(false)), "false");
    }

    #[test]
    fn test_format_value_preview_number() {
        assert_eq!(format_value_preview(&serde_json::json!(42)), "42");
        assert_eq!(format_value_preview(&serde_json::json!(1.5)), "1.5");
    }

    // ===== truncate_lines tests =====

    #[test]
    fn test_truncate_lines_no_truncation() {
        let text = "line1\nline2\nline3";
        let (result, remaining) = truncate_lines(text, 5);
        assert_eq!(result, text);
        assert_eq!(remaining, 0);
    }

    #[test]
    fn test_truncate_lines_with_truncation() {
        let text = "line1\nline2\nline3\nline4\nline5";
        let (result, remaining) = truncate_lines(text, 3);
        assert_eq!(result, "line1\nline2\nline3");
        assert_eq!(remaining, 2);
    }

    #[test]
    fn test_truncate_lines_exact_limit() {
        let text = "line1\nline2\nline3";
        let (result, remaining) = truncate_lines(text, 3);
        assert_eq!(result, text);
        assert_eq!(remaining, 0);
    }

    // ===== format_params tests =====

    #[test]
    fn test_format_params_plain_simple() {
        let params = serde_json::json!({"path": "/tmp/test.txt"});
        let output = format_params_plain("read_file", &params);

        assert!(output.starts_with("read_file"));
        assert!(output.contains("path:"));
        assert!(output.contains("/tmp/test.txt"));
    }

    #[test]
    fn test_format_params_plain_many_params() {
        // More than MAX_PARAMS (10) parameters
        let mut obj = serde_json::Map::new();
        for i in 0..15 {
            obj.insert(format!("key{}", i), serde_json::json!(i));
        }
        let params = serde_json::Value::Object(obj);
        let output = format_params_plain("test_tool", &params);

        assert!(output.contains("… +"));
        assert!(output.contains("more"));
    }

    #[test]
    fn test_format_params_ansi_has_codes() {
        let params = serde_json::json!({"name": "test"});
        let output = format_params_ansi("my_tool", &params);

        // Should contain ANSI escape codes
        assert!(output.contains("\x1b["));
        // Should contain tool name
        assert!(output.contains("my_tool"));
    }

    #[test]
    fn test_format_params_markdown_format() {
        let params = serde_json::json!({"file": "test.rs"});
        let output = format_params_markdown("edit", &params);

        // Should have bold tool name
        assert!(output.starts_with("**edit**"));
        // Should have markdown list items
        assert!(output.contains("- `file`:"));
    }

    // ===== format_result tests =====

    #[test]
    fn test_format_result_plain_short() {
        let result = ToolResult::Text("Success!".to_string());
        let output = format_result_plain(&result);
        assert_eq!(output, "Success!");
    }

    #[test]
    fn test_format_result_plain_truncated() {
        // More than MAX_OUTPUT_LINES (12) lines
        let long_text = (0..20)
            .map(|i| format!("line {}", i))
            .collect::<Vec<_>>()
            .join("\n");
        let result = ToolResult::Text(long_text);
        let output = format_result_plain(&result);

        assert!(output.contains("… +"));
        assert!(output.contains("more lines"));
    }

    #[test]
    fn test_format_result_ansi_success_marker() {
        let result = ToolResult::Text("Done".to_string());
        let output = format_result_ansi(&result);

        // Should have green checkmark
        assert!(output.contains("\x1b[32m✓\x1b[0m"));
    }

    #[test]
    fn test_format_result_markdown_code_block() {
        let result = ToolResult::Text("code here".to_string());
        let output = format_result_markdown(&result);

        assert!(output.starts_with("```\n"));
        assert!(output.contains("code here"));
        assert!(output.contains("\n```"));
    }

    #[test]
    fn test_format_result_json() {
        let result = ToolResult::Json(serde_json::json!({"status": "ok"}));
        let output = format_result_plain(&result);

        // JSON should be pretty-printed
        assert!(output.contains("status"));
        assert!(output.contains("ok"));
    }

    #[test]
    fn test_format_result_image() {
        let result = ToolResult::Image {
            format: ImageFormat::Png,
            data: vec![0u8; 1000],
        };
        let output = format_result_plain(&result);

        assert!(output.contains("Image"));
        assert!(output.contains("Png"));
        assert!(output.contains("1000 bytes"));
    }

    #[test]
    fn test_format_result_document() {
        let result = ToolResult::Document {
            format: DocumentFormat::Pdf,
            data: vec![0u8; 500],
            name: Some("report.pdf".to_string()),
        };
        let output = format_result_plain(&result);

        assert!(output.contains("Document"));
        assert!(output.contains("Pdf"));
        assert!(output.contains("report.pdf"));
        assert!(output.contains("500 bytes"));
    }

    #[test]
    fn test_format_result_document_unnamed() {
        let result = ToolResult::Document {
            format: DocumentFormat::Txt,
            data: vec![0u8; 100],
            name: None,
        };
        let output = format_result_plain(&result);

        assert!(output.contains("unnamed"));
    }

    // ===== ToolResult factory tests =====

    #[test]
    fn test_tool_result_image_factory() {
        let result = ToolResult::image(ImageFormat::Jpeg, vec![1, 2, 3]);

        if let ToolResult::Image { format, data } = result {
            assert_eq!(format, ImageFormat::Jpeg);
            assert_eq!(data, vec![1, 2, 3]);
        } else {
            panic!("Expected Image variant");
        }
    }

    #[test]
    fn test_tool_result_document_factory() {
        let result = ToolResult::document(DocumentFormat::Csv, vec![4, 5, 6]);

        if let ToolResult::Document { format, data, name } = result {
            assert_eq!(format, DocumentFormat::Csv);
            assert_eq!(data, vec![4, 5, 6]);
            assert!(name.is_none());
        } else {
            panic!("Expected Document variant");
        }
    }

    #[test]
    fn test_tool_result_document_with_name_factory() {
        let result = ToolResult::document_with_name(DocumentFormat::Html, vec![7, 8], "page.html");

        if let ToolResult::Document { format, data, name } = result {
            assert_eq!(format, DocumentFormat::Html);
            assert_eq!(data, vec![7, 8]);
            assert_eq!(name, Some("page.html".to_string()));
        } else {
            panic!("Expected Document variant");
        }
    }

    // ===== ToolResult::as_text for binary types =====

    #[test]
    fn test_tool_result_as_text_image() {
        let result = ToolResult::Image {
            format: ImageFormat::Gif,
            data: vec![0u8; 2000],
        };
        let text = result.as_text();

        assert!(text.contains("Image"));
        assert!(text.contains("Gif"));
        assert!(text.contains("2000 bytes"));
    }

    #[test]
    fn test_tool_result_as_text_document() {
        let result = ToolResult::Document {
            format: DocumentFormat::Xlsx,
            data: vec![0u8; 3000],
            name: Some("data.xlsx".to_string()),
        };
        let text = result.as_text();

        assert!(text.contains("Document"));
        assert!(text.contains("Xlsx"));
        assert!(text.contains("data.xlsx"));
        assert!(text.contains("3000 bytes"));
    }

    #[test]
    fn test_tool_result_as_str_binary_types() {
        let image = ToolResult::Image {
            format: ImageFormat::Webp,
            data: vec![],
        };
        assert!(image.as_str().is_none());

        let doc = ToolResult::Document {
            format: DocumentFormat::Doc,
            data: vec![],
            name: None,
        };
        assert!(doc.as_str().is_none());
    }
}