Skip to main content

agentic_tools_core/
fmt.rs

1//! Transport-agnostic text formatting for tool outputs.
2//!
3//! This module provides the [`TextFormat`] trait for converting tool outputs to
4//! human-readable text, along with supporting types and helpers.
5//!
6//! # Usage
7//!
8//! Tool outputs must implement [`TextFormat`]. The trait provides a default
9//! implementation that returns pretty-printed JSON via the `Serialize` supertrait.
10//! Types can override `fmt_text` for custom human-friendly formatting:
11//!
12//! ```ignore
13//! use agentic_tools_core::fmt::{TextFormat, TextOptions};
14//! use serde::Serialize;
15//!
16//! #[derive(Serialize)]
17//! struct MyOutput {
18//!     count: usize,
19//!     items: Vec<String>,
20//! }
21//!
22//! // Use default (pretty JSON):
23//! impl TextFormat for MyOutput {}
24//!
25//! // Or provide custom formatting:
26//! impl TextFormat for MyOutput {
27//!     fn fmt_text(&self, opts: &TextOptions) -> String {
28//!         format!("Found {} items:\n{}", self.count, self.items.join("\n"))
29//!     }
30//! }
31//! ```
32//!
33//! # Default TextFormat Fallback
34//!
35//! The [`TextFormat`] trait requires `Serialize` and provides a default `fmt_text`
36//! implementation that produces pretty-printed JSON. This means:
37//!
38//! - Types with custom formatting override `fmt_text()`
39//! - Types wanting JSON fallback use an empty impl: `impl TextFormat for T {}`
40//! - The registry always calls `fmt_text()` on the native output—no detection needed
41
42use serde_json::Value as JsonValue;
43use std::any::Any;
44
45/// Text rendering style.
46#[derive(Clone, Debug, Default, PartialEq, Eq)]
47pub enum TextStyle {
48    /// Human-friendly formatting with Unicode symbols and formatting.
49    #[default]
50    Humanized,
51    /// Plain text without special formatting.
52    Plain,
53}
54
55/// Options controlling text formatting behavior.
56#[derive(Clone, Debug, Default)]
57pub struct TextOptions {
58    /// The rendering style to use.
59    pub style: TextStyle,
60    /// Whether to wrap output in markdown formatting.
61    pub markdown: bool,
62    /// Maximum number of items to display in collections.
63    pub max_items: Option<usize>,
64}
65
66impl TextOptions {
67    /// Create new text options with default settings.
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// Set the text style.
73    pub fn with_style(mut self, style: TextStyle) -> Self {
74        self.style = style;
75        self
76    }
77
78    /// Enable or disable markdown formatting.
79    pub fn with_markdown(mut self, markdown: bool) -> Self {
80        self.markdown = markdown;
81        self
82    }
83
84    /// Set the maximum number of items to display.
85    pub fn with_max_items(mut self, max_items: Option<usize>) -> Self {
86        self.max_items = max_items;
87        self
88    }
89}
90
91/// Transport-agnostic text formatting for tool outputs.
92///
93/// Implement this trait to provide custom human-readable formatting for your
94/// tool output types. The formatting is used by both MCP and NAPI servers
95/// to produce text alongside JSON data.
96///
97/// The default implementation returns pretty-printed JSON. Types can override
98/// `fmt_text` to provide custom human-friendly formatting.
99pub trait TextFormat: serde::Serialize {
100    /// Format the value as human-readable text.
101    ///
102    /// Default: pretty-printed JSON. Types can override to provide custom
103    /// human-friendly formatting.
104    fn fmt_text(&self, _opts: &TextOptions) -> String {
105        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
106    }
107}
108
109/// Pretty JSON fallback used when a type does not implement [`TextFormat`].
110///
111/// This produces a nicely indented JSON string, or falls back to compact
112/// JSON if pretty-printing fails.
113pub fn fallback_text_from_json(v: &JsonValue) -> String {
114    serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string())
115}
116
117/// Identity formatter for String: returns the raw string without JSON quoting.
118impl TextFormat for String {
119    fn fmt_text(&self, _opts: &TextOptions) -> String {
120        self.clone()
121    }
122}
123
124// ============================================================================
125// Type-erased formatter infrastructure (compatibility API)
126// ============================================================================
127//
128// This infrastructure is preserved for compatibility with external crates.
129// The registry now calls `TextFormat::fmt_text()` directly on tool outputs,
130// so this type-erased machinery is no longer used internally.
131
132/// Type-erased formatter function signature.
133///
134/// Takes a reference to the wire output (as `&dyn Any`), the JSON data (for fallback),
135/// and formatting options. Returns `Some(text)` if formatting succeeded.
136type ErasedFmtFn = fn(&dyn Any, &JsonValue, &TextOptions) -> Option<String>;
137
138/// Type-erased formatter captured at tool registration time.
139///
140/// This stores an optional formatting function that will be called at runtime
141/// to produce human-readable text from tool output. If `None`, the registry
142/// falls back to pretty-printed JSON.
143#[derive(Clone, Copy)]
144pub struct ErasedFmt {
145    fmt_fn: Option<ErasedFmtFn>,
146}
147
148impl ErasedFmt {
149    /// Create an empty formatter (will use JSON fallback).
150    pub const fn none() -> Self {
151        Self { fmt_fn: None }
152    }
153
154    /// Attempt to format the given wire output.
155    ///
156    /// Returns `Some(text)` if this formatter has a function and it succeeded,
157    /// `None` otherwise (caller should use JSON fallback).
158    pub fn format(
159        &self,
160        wire_any: &dyn Any,
161        data: &JsonValue,
162        opts: &TextOptions,
163    ) -> Option<String> {
164        self.fmt_fn.and_then(|f| f(wire_any, data, opts))
165    }
166}
167
168impl std::fmt::Debug for ErasedFmt {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        f.debug_struct("ErasedFmt")
171            .field("has_formatter", &self.fmt_fn.is_some())
172            .finish()
173    }
174}
175
176/// Build a formatter for a type that implements [`TextFormat`].
177///
178/// This is the explicit builder used when you know the type implements `TextFormat`.
179/// Kept for compatibility with external crates that may use the `ErasedFmt` API.
180pub fn build_formatter_for_textformat<W>() -> ErasedFmt
181where
182    W: TextFormat + Send + 'static,
183{
184    ErasedFmt {
185        fmt_fn: Some(|any, _json, opts| any.downcast_ref::<W>().map(|w| w.fmt_text(opts))),
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn test_text_style_default() {
195        let style = TextStyle::default();
196        assert_eq!(style, TextStyle::Humanized);
197    }
198
199    #[test]
200    fn test_text_options_default() {
201        let opts = TextOptions::default();
202        assert_eq!(opts.style, TextStyle::Humanized);
203        assert!(!opts.markdown);
204        assert!(opts.max_items.is_none());
205    }
206
207    #[test]
208    fn test_text_options_builder() {
209        let opts = TextOptions::new()
210            .with_style(TextStyle::Plain)
211            .with_markdown(true)
212            .with_max_items(Some(10));
213
214        assert_eq!(opts.style, TextStyle::Plain);
215        assert!(opts.markdown);
216        assert_eq!(opts.max_items, Some(10));
217    }
218
219    #[test]
220    fn test_fallback_text_from_json_object() {
221        let v = serde_json::json!({"name": "test", "count": 42});
222        let text = fallback_text_from_json(&v);
223        assert!(text.contains("\"name\": \"test\""));
224        assert!(text.contains("\"count\": 42"));
225    }
226
227    #[test]
228    fn test_fallback_text_from_json_array() {
229        let v = serde_json::json!([1, 2, 3]);
230        let text = fallback_text_from_json(&v);
231        assert!(text.contains("1"));
232        assert!(text.contains("2"));
233        assert!(text.contains("3"));
234    }
235
236    #[test]
237    fn test_fallback_text_from_json_null() {
238        let v = serde_json::json!(null);
239        let text = fallback_text_from_json(&v);
240        assert_eq!(text, "null");
241    }
242
243    #[test]
244    fn test_text_format_impl() {
245        #[derive(serde::Serialize)]
246        struct TestOutput {
247            message: String,
248        }
249
250        impl TextFormat for TestOutput {
251            fn fmt_text(&self, _opts: &TextOptions) -> String {
252                format!("Message: {}", self.message)
253            }
254        }
255
256        let output = TestOutput {
257            message: "Hello".to_string(),
258        };
259        let text = output.fmt_text(&TextOptions::default());
260        assert_eq!(text, "Message: Hello");
261    }
262}