mercutio 0.7.2

IO-less MCP server library
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
//! Tool registration types and macros.
//!
//! Provides type-safe tool registration for MCP servers. The [`tool_registry!`] macro generates
//! input structs, a dispatch enum, and [`ToolRegistry`] implementation from a single declaration.
//!
//! # Tool Output Format
//!
//! Prefer plain text over JSON for content the LLM will reason about. Research shows JSON-mode
//! degrades LLM reasoning performance (see <https://arxiv.org/abs/2408.02442>). Use JSON
//! ([`ToolOutput::json`]) only when the output needs programmatic parsing downstream. For tool
//! results the LLM will interpret and relay to users, return human-readable text:
//!
//! ```ignore
//! // Good: readable text the LLM can reason about
//! Ok(format!("Temperature: {}F\nConditions: {}", temp, conditions))
//!
//! // Avoid: JSON for LLM consumption
//! Ok(ToolOutput::json(&WeatherData { temp, conditions }))
//! ```
//!
//! # Snapshot Testing
//!
//! Both [`ToolDefinitions`] and [`ToolOutput`] implement [`Display`] for snapshot testing with
//! `insta`. Use this to verify tool schemas and outputs:
//!
//! ```ignore
//! #[test]
//! fn tool_schemas_are_stable() {
//!     insta::assert_snapshot!(MyTools::definitions().to_string(), @r"
//!     # Tools
//!
//!     ## get_weather
//!     ...
//!     ");
//! }
//!
//! #[test]
//! fn weather_output_format() {
//!     let output = get_weather("Berlin").await?;
//!     insta::assert_snapshot!(output.to_string(), @r"
//!     Temperature: 72F
//!
//!     Conditions: Sunny
//!     ");
//! }
//! ```
//!
//! For raw JSON schema snapshots, note that [`ToolInputSchema`] uses `HashMap` internally, causing
//! non-deterministic key ordering. Serialize via [`serde_json::to_value`] first to convert to
//! `serde_json::Map` (BTreeMap-backed) for stable output:
//!
//! ```ignore
//! let def = ToolDefinition::from_tool::<MyTool>();
//! let json = serde_json::to_value(&def.input_schema).unwrap();
//! insta::assert_snapshot!(serde_json::to_string_pretty(&json).unwrap());
//! ```
//!
//! This workaround only affects snapshot testing; the actual MCP wire protocol still serializes
//! with non-deterministic key order. See <https://github.com/rust-mcp-stack/rust-mcp-schema/pull/105>
//! for the upstream fix.

use std::{collections::HashMap, fmt, ops::Index};

use base64::Engine;
use rust_mcp_schema::{
    AudioContent, BlobResourceContents, CallToolResult, ContentBlock, EmbeddedResource,
    ImageContent, ResourceLink, TextResourceContents, ToolInputSchema,
};
use serde::Serialize;

use crate::JsonRpcError;

/// Defines a tool's input type and metadata.
///
/// Implement this trait on tool input structs to associate them with MCP metadata. The
/// [`tool_registry`](crate::tool_registry) macro generates this implementation automatically.
pub trait ToolDef: schemars::JsonSchema + serde::de::DeserializeOwned + 'static {
    /// Tool name as it appears in the MCP protocol.
    const NAME: &'static str;
    /// Human-readable description of what the tool does.
    const DESCRIPTION: &'static str;
}

/// Successful output from a tool invocation.
///
/// Provides a builder API and ergonomic conversions for constructing tool output. For domain
/// errors (tool ran but failed), return an `Err` from your handler instead of using this type.
///
/// # Text vs JSON
///
/// Prefer plain text for tool outputs the LLM will reason about. Research shows JSON-mode
/// degrades reasoning performance (see [module docs](self) for details). Reserve
/// [`ToolOutput::json`] for data that needs programmatic parsing downstream.
///
/// ```ignore
/// // Recommended: human-readable text
/// Ok(format!("Temperature: {}F\nConditions: {}", temp, conditions))
///
/// // Use only when structured parsing is needed downstream
/// Ok(ToolOutput::json(&data))
/// ```
///
/// # Simple Text
///
/// Return a text response (accepts `&str`, [`String`], or [`format!`] results):
/// ```ignore
/// Ok("Operation completed")
/// Ok(format!("Found {} items", count))
/// ```
///
/// # Structured JSON
///
/// Return structured data with [`ToolOutput::json`]. This sets `structuredContent` and adds
/// the JSON as escaped text for backwards compatibility (per MCP spec). Only use this when the
/// output requires programmatic parsing:
/// ```ignore
/// Ok(ToolOutput::json(&api_response))
/// ```
///
/// # Multiple Content Blocks
///
/// Combine multiple content blocks using the builder:
/// ```ignore
/// Ok(ToolOutput::new()
///     .text("Query results:")
///     .text(format!("Found {} matches", results.len())))
/// ```
///
/// # Snapshot Testing
///
/// `ToolOutput` implements [`Display`] for snapshot testing with `insta`. This renders text
/// blocks directly and shows placeholders for binary content (images, audio, embedded resources):
///
/// ```ignore
/// #[test]
/// fn weather_tool_output() {
///     let output = get_weather_handler(input).await?;
///     insta::assert_snapshot!(output.to_string(), @r"
///     Temperature: 72F
///
///     Conditions: Sunny
///     ");
/// }
/// ```
#[derive(Debug, Default)]
pub struct ToolOutput {
    /// Content blocks.
    content: Vec<ContentBlock>,
    /// Structured content.
    structured_content: Option<serde_json::Map<String, serde_json::Value>>,
}

impl ToolOutput {
    /// Creates an empty output for building.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates output with structured JSON content and text representation.
    ///
    /// Sets `structuredContent` and adds the JSON as escaped text to `content` for backwards
    /// compatibility (per MCP spec recommendation).
    ///
    /// # Panics
    ///
    /// Will panic if serialization of `T` fails.
    pub fn json<T: Serialize>(value: &T) -> Self {
        let text = serde_json::to_string(value).expect("serialization failed");
        Self::new().text(text).structured(value)
    }

    /// Adds a text content block.
    pub fn text<I: Into<String>>(mut self, text: I) -> Self {
        self.content.push(ContentBlock::text_content(text.into()));
        self
    }

    /// Adds an image content block.
    ///
    /// The image data is base64-encoded automatically.
    pub fn image<S: Into<String>>(mut self, data: &[u8], mime_type: S) -> Self {
        let encoded = base64::engine::general_purpose::STANDARD.encode(data);
        self.content
            .push(ImageContent::new(encoded, mime_type.into(), None, None).into());
        self
    }

    /// Adds an audio content block.
    ///
    /// The audio data is base64-encoded automatically.
    pub fn audio<S: Into<String>>(mut self, data: &[u8], mime_type: S) -> Self {
        let encoded = base64::engine::general_purpose::STANDARD.encode(data);
        self.content
            .push(AudioContent::new(encoded, mime_type.into(), None, None).into());
        self
    }

    /// Adds an embedded blob resource.
    ///
    /// Use for binary content with URI metadata, such as PDFs or other documents. The data is
    /// base64-encoded automatically.
    pub fn embedded_blob<U: Into<String>, M: Into<String>>(
        mut self,
        data: &[u8],
        uri: U,
        mime_type: M,
    ) -> Self {
        let encoded = base64::engine::general_purpose::STANDARD.encode(data);
        let blob = BlobResourceContents {
            blob: encoded,
            uri: uri.into(),
            mime_type: Some(mime_type.into()),
            meta: None,
        };
        self.content
            .push(EmbeddedResource::new(blob.into(), None, None).into());
        self
    }

    /// Adds an embedded text resource.
    ///
    /// Like [`text`](Self::text) but includes a URI, useful when the content represents a file
    /// or addressable resource.
    pub fn embedded_text<T: Into<String>, U: Into<String>, M: Into<String>>(
        mut self,
        text: T,
        uri: U,
        mime_type: Option<M>,
    ) -> Self {
        let text_resource = TextResourceContents {
            text: text.into(),
            uri: uri.into(),
            mime_type: mime_type.map(Into::into),
            meta: None,
        };
        self.content
            .push(EmbeddedResource::new(text_resource.into(), None, None).into());
        self
    }

    /// Adds a resource link.
    ///
    /// References an MCP resource by URI rather than embedding content inline. The client
    /// fetches it separately via `resources/read`.
    pub fn resource_link<U: Into<String>, N: Into<String>>(mut self, uri: U, name: N) -> Self {
        self.content.push(
            ResourceLink::new(name.into(), uri.into(), None, None, None, None, None, None).into(),
        );
        self
    }

    /// Adds a raw content block.
    ///
    /// Use this for content types not covered by the convenience methods ([`text`](Self::text),
    /// [`image`](Self::image), [`audio`](Self::audio)). Types from [`rust_mcp_schema`] that
    /// implement `Into<ContentBlock>` can be passed directly:
    ///
    /// ```ignore
    /// use mercutio::rust_mcp_schema::{EmbeddedResource, BlobResourceContents};
    ///
    /// ToolOutput::new().content(EmbeddedResource {
    ///     resource: BlobResourceContents { ... }.into(),
    ///     ...
    /// })
    /// ```
    pub fn content(mut self, block: impl Into<ContentBlock>) -> Self {
        self.content.push(block.into());
        self
    }

    /// Sets structured content.
    ///
    /// Sets `structuredContent` to the serialized value. Does not modify `content`; use
    /// [`Self::json`] or add a text block manually for backwards compatibility.
    pub fn structured<T: Serialize>(mut self, value: &T) -> Self {
        let json_value = serde_json::to_value(value).expect("serialization failed");
        if let serde_json::Value::Object(map) = json_value {
            self.structured_content = Some(map);
        }
        self
    }

    /// Returns the content blocks.
    pub fn content_blocks(&self) -> &[ContentBlock] {
        &self.content
    }

    /// Returns the structured content, if set.
    pub fn structured_content(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
        self.structured_content.as_ref()
    }

    /// Returns the text if output contains exactly one text block.
    pub fn as_text(&self) -> Option<&str> {
        match self.content.as_slice() {
            [ContentBlock::TextContent(text)] => Some(&text.text),
            _ => None,
        }
    }

    /// Converts to the MCP [`CallToolResult`] with the given error flag.
    fn into_call_result(self, is_error: bool) -> CallToolResult {
        CallToolResult {
            content: self.content,
            is_error: Some(is_error),
            structured_content: self.structured_content,
            meta: None,
        }
    }
}

impl fmt::Display for ToolOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, block) in self.content.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
                writeln!(f)?;
            }
            match block {
                ContentBlock::TextContent(text) => {
                    write!(f, "{}", text.text)?;
                }
                ContentBlock::ImageContent(img) => {
                    write!(f, "[Image: {}, {} bytes]", img.mime_type, img.data.len())?;
                }
                ContentBlock::AudioContent(audio) => {
                    write!(
                        f,
                        "[Audio: {}, {} bytes]",
                        audio.mime_type,
                        audio.data.len()
                    )?;
                }
                ContentBlock::ResourceLink(link) => {
                    write!(f, "[Resource: {} ({})]", link.name, link.uri)?;
                }
                ContentBlock::EmbeddedResource(res) => {
                    use rust_mcp_schema::EmbeddedResourceResource;
                    match &res.resource {
                        EmbeddedResourceResource::TextResourceContents(text) => {
                            write!(f, "[Embedded Text: {}]", text.uri)?;
                        }
                        EmbeddedResourceResource::BlobResourceContents(blob) => {
                            let mime = blob.mime_type.as_deref().unwrap_or("unknown");
                            write!(
                                f,
                                "[Embedded Blob: {}, {}, {} bytes]",
                                blob.uri,
                                mime,
                                blob.blob.len()
                            )?;
                        }
                    }
                }
            }
        }

        if let Some(structured) = &self.structured_content {
            if !self.content.is_empty() {
                writeln!(f)?;
                writeln!(f)?;
            }
            writeln!(f, "Structured Content:")?;
            let json = serde_json::to_string_pretty(structured).unwrap_or_default();
            write!(f, "{}", json)?;
        }

        Ok(())
    }
}

impl From<String> for ToolOutput {
    fn from(text: String) -> Self {
        Self::new().text(text)
    }
}

impl From<&str> for ToolOutput {
    fn from(text: &str) -> Self {
        Self::new().text(text)
    }
}

/// Converts a value into a tool response ([`CallToolResult`]).
///
/// This trait enables [`Responder::respond`](crate::Responder::respond) to accept both direct
/// values and `Result` types:
///
/// - **Direct values** (`String`, `&str`, [`ToolOutput`]): Converted to a successful response
///   with `is_error: false`.
/// - **`Result<T, E>`**: `Ok(v)` becomes a successful response; `Err(e)` becomes a domain error
///   response with `is_error: true` and the error's display text as content.
pub trait IntoToolResponse {
    /// Converts this value into a [`CallToolResult`].
    fn into_tool_response(self) -> CallToolResult;
}

impl IntoToolResponse for ToolOutput {
    fn into_tool_response(self) -> CallToolResult {
        self.into_call_result(false)
    }
}

impl IntoToolResponse for String {
    fn into_tool_response(self) -> CallToolResult {
        ToolOutput::from(self).into_call_result(false)
    }
}

impl IntoToolResponse for &str {
    fn into_tool_response(self) -> CallToolResult {
        ToolOutput::from(self).into_call_result(false)
    }
}

impl<T, E> IntoToolResponse for Result<T, E>
where
    T: Into<ToolOutput>,
    E: std::fmt::Display,
{
    fn into_tool_response(self) -> CallToolResult {
        match self {
            Ok(v) => v.into().into_call_result(false),
            Err(e) => ToolOutput::new().text(e.to_string()).into_call_result(true),
        }
    }
}

/// Wrapper that formats the full error chain for tool responses.
///
/// By default, tool errors only show the top-level message from [`Display`]. When using
/// `thiserror` with `#[source]`, nested error causes are attached but not displayed. This wrapper
/// traverses the [`Error::source`](std::error::Error::source) chain to produce a complete message
/// like `"google API error: HTTP request failed: connection refused"`.
///
/// This pattern follows the design from
/// [The elements of Rust error handling](https://compilersaysno.com/posts/the-elements-of-rust-error-handling/):
/// keep `Display` impls minimal and let callers decide when to show the full chain.
///
/// # When to Use
///
/// Use `WithSource` when your error type has nested causes that would help the LLM understand
/// what went wrong. This is especially useful for errors from external services, I/O operations,
/// or any chain where the root cause provides actionable information.
///
/// # Example
///
/// ```ignore
/// use mercutio::WithSource;
///
/// async fn handle_tool(tool: MyTools) -> Result<String, WithSource<MyError>> {
///     let data = fetch_api().map_err(WithSource)?;
///     Ok(format!("Got: {data}"))
/// }
/// ```
///
/// Without `WithSource`, an API failure might show: `"API request failed"`
///
/// With `WithSource`, it shows: `"API request failed: HTTP error: 403 Forbidden"`
#[derive(Debug)]
pub struct WithSource<E>(pub E);

impl<E: std::error::Error> fmt::Display for WithSource<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)?;
        let mut current: &dyn std::error::Error = &self.0;
        while let Some(source) = current.source() {
            write!(f, ": {}", source)?;
            current = source;
        }
        Ok(())
    }
}

impl<E: std::error::Error> std::error::Error for WithSource<E> {}

impl<E: std::error::Error> From<E> for WithSource<E> {
    fn from(err: E) -> Self {
        Self(err)
    }
}

/// MCP tool definition for `tools/list` responses.
#[derive(Debug)]
pub struct ToolDefinition {
    /// Tool name.
    pub name: String,
    /// Tool description.
    pub description: String,
    /// JSON Schema for the input parameters.
    pub input_schema: ToolInputSchema,
}

impl ToolDefinition {
    /// Creates a definition from a type implementing [`ToolDef`].
    pub fn from_tool<T: ToolDef>() -> Self {
        let settings = schemars::r#gen::SchemaSettings::draft07().with(|s| {
            s.option_add_null_type = false;
        });
        let schema = settings.into_generator().into_root_schema_for::<T>();
        let json = serde_json::to_value(&schema).expect("schema serialization failed");
        let input_schema = convert_schema_to_tool_input(&json);
        Self {
            name: T::NAME.to_string(),
            description: T::DESCRIPTION.to_string(),
            input_schema,
        }
    }

    /// Converts to the MCP schema [`Tool`](rust_mcp_schema::Tool) type.
    pub fn into_mcp_tool(self) -> rust_mcp_schema::Tool {
        rust_mcp_schema::Tool {
            name: self.name,
            description: Some(self.description),
            input_schema: self.input_schema,
            annotations: None,
            meta: None,
            output_schema: None,
            title: None,
        }
    }
}

impl fmt::Display for ToolDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "## {}", self.name)?;
        writeln!(f)?;
        writeln!(f, "{}", self.description)?;

        let Some(props) = &self.input_schema.properties else {
            return Ok(());
        };
        if props.is_empty() {
            return Ok(());
        }

        writeln!(f)?;
        writeln!(f, "Parameters:")?;

        let mut names: Vec<_> = props.keys().collect();
        names.sort();

        for name in names {
            let prop = &props[name];
            let required = self.input_schema.required.contains(name);
            let req_str = if required { "required" } else { "optional" };

            let type_str = prop.get("type").and_then(|v| v.as_str()).unwrap_or("any");

            write!(f, "  {name} ({type_str}, {req_str})")?;

            if let Some(desc) = prop.get("description").and_then(|v| v.as_str()) {
                writeln!(f)?;
                write!(f, "    {desc}")?;
            }

            if let Some(enum_vals) = prop.get("enum").and_then(|v| v.as_array()) {
                let vals: Vec<_> = enum_vals.iter().filter_map(|v| v.as_str()).collect();
                if !vals.is_empty() {
                    writeln!(f)?;
                    write!(f, "    Values: {}", vals.join(", "))?;
                }
            }

            writeln!(f)?;
        }

        Ok(())
    }
}

/// Collection of tool definitions returned by [`ToolRegistry::definitions`].
///
/// Implements [`Display`] to render all tools as a human-readable document. This lets you see
/// exactly what the LLM receives when it queries your MCP server's available tools, making it
/// easy to verify tool names, descriptions, and parameter schemas.
///
/// # Snapshot Testing with Insta
///
/// Use `insta` inline snapshots to catch unintended changes to your tool schemas:
///
/// ```ignore
/// use mercutio::ToolRegistry;
///
/// #[test]
/// fn tool_schemas_are_stable() {
///     // The snapshot is stored inline - run `cargo insta test` to update
///     insta::assert_snapshot!(MyTools::definitions().to_string(), @r"
///     # Tools
///
///     ## get_weather
///
///     Gets current weather for a location
///
///     Parameters:
///       location (string, required)
///         City name or address
///     ");
/// }
/// ```
///
/// When you change a tool's name, description, or parameters, the test fails and `cargo insta
/// review` shows the diff. This ensures schema changes are intentional and documented.
#[derive(Debug)]
pub struct ToolDefinitions(Vec<ToolDefinition>);

impl ToolDefinitions {
    /// Creates a new collection from a vector of definitions.
    pub fn new(definitions: Vec<ToolDefinition>) -> Self {
        Self(definitions)
    }

    /// Returns the number of tool definitions.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if there are no tool definitions.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns an iterator over the tool definitions.
    pub fn iter(&self) -> impl Iterator<Item = &ToolDefinition> {
        self.0.iter()
    }
}

impl Index<usize> for ToolDefinitions {
    type Output = ToolDefinition;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl IntoIterator for ToolDefinitions {
    type Item = ToolDefinition;
    type IntoIter = std::vec::IntoIter<ToolDefinition>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a ToolDefinitions {
    type Item = &'a ToolDefinition;
    type IntoIter = std::slice::Iter<'a, ToolDefinition>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl fmt::Display for ToolDefinitions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "# Tools")?;
        writeln!(f)?;

        for (i, def) in self.0.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
            }
            write!(f, "{def}")?;
        }

        Ok(())
    }
}

/// Converts a schemars JSON Schema to MCP's [`ToolInputSchema`].
///
/// MCP tools use standard JSON Schema for `inputSchema`. We use `schemars` to derive schemas from
/// Rust types, but [`ToolInputSchema`] only models `properties` and `required`, discarding metadata
/// like `$schema`, `title`, and `definitions`. This breaks nested struct types since schemars emits
/// `$ref` pointers into the discarded `definitions`. Workaround: annotate nested types with
/// `#[schemars(inline)]` to force inlining, or keep tool inputs flat.
fn convert_schema_to_tool_input(schema: &serde_json::Value) -> ToolInputSchema {
    let required = schema
        .get("required")
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let properties = schema
        .get("properties")
        .and_then(|p| p.as_object())
        .map(|obj| {
            obj.iter()
                .map(|(k, v)| {
                    let map = v.as_object().cloned().unwrap_or_default();
                    (k.clone(), map)
                })
                .collect::<HashMap<_, _>>()
        });

    ToolInputSchema::new(required, properties)
}

/// Registry of available tools.
///
/// Typically implemented by enums representing the set of tools a server supports, where each
/// variant corresponds to a tool and contains its parsed input. The [`tool_registry`] macro
/// generates this implementation automatically.
///
/// For testing individual tools, any [`ToolDef`] can be used directly as a single-tool registry
/// via the blanket impl, without needing to define a registry enum:
///
/// ```ignore
/// let server = McpServer::<GetWeather>::builder()
///     .name("test-server")
///     .version("1.0")
///     .build();
/// ```
pub trait ToolRegistry: Sized {
    /// Whether tools are enabled. Used to advertise tool capabilities during init.
    const ENABLED: bool = true;

    /// Parses a tool call into a typed enum variant.
    fn parse(name: &str, arguments: serde_json::Value) -> std::result::Result<Self, JsonRpcError>;

    /// Returns tool definitions for `tools/list`.
    fn definitions() -> ToolDefinitions;
}

/// Empty tool registry for servers that don't expose tools.
///
/// This is the default type parameter for [`McpServer`](crate::McpServer), so the turbofish can
/// be omitted: `McpServer::builder()` instead of `McpServer::<NoTools>::builder()`.
#[derive(Debug)]
pub enum NoTools {}

impl ToolRegistry for NoTools {
    const ENABLED: bool = false;

    fn parse(name: &str, _arguments: serde_json::Value) -> std::result::Result<Self, JsonRpcError> {
        Err(JsonRpcError::MethodNotFound {
            msg: format!("unknown tool: {name}"),
        })
    }

    fn definitions() -> ToolDefinitions {
        ToolDefinitions::new(vec![])
    }
}

impl<T: ToolDef> ToolRegistry for T {
    fn parse(name: &str, arguments: serde_json::Value) -> std::result::Result<Self, JsonRpcError> {
        if name == T::NAME {
            serde_json::from_value(arguments).map_err(|e| JsonRpcError::InvalidParams {
                msg: format!("{}: {e}", T::NAME),
            })
        } else {
            Err(JsonRpcError::MethodNotFound {
                msg: format!("unknown tool: {name}"),
            })
        }
    }

    fn definitions() -> ToolDefinitions {
        ToolDefinitions::new(vec![ToolDefinition::from_tool::<T>()])
    }
}

/// Generates tool input structs, a dispatch enum, and [`ToolRegistry`] implementation.
///
/// Doc comments (`///`) on struct fields become JSON Schema descriptions, which are sent to
/// clients during `tools/list` and help the LLM understand how to use each parameter.
///
/// # Nested Types
///
/// Field types that are custom structs must be annotated with `#[schemars(inline)]`, otherwise
/// the generated JSON Schema will contain unresolved `$ref` pointers. Enums and primitive types
/// work without this annotation.
///
/// ```ignore
/// #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
/// #[schemars(inline)]  // Required for nested struct types
/// struct Location {
///     city: String,
///     country: String,
/// }
/// ```
///
/// # Example
///
/// ```ignore
/// tool_registry! {
///     enum MyTools {
///         GetWeather("get_weather", "Gets weather for a city") {
///             /// City name, e.g. "San Francisco"
///             city: String,
///             /// Temperature units (celsius or fahrenheit)
///             units: Option<Units>,
///         },
///
///         SetReminder("set_reminder", "Sets a reminder") {
///             /// Reminder text
///             text: String,
///         },
///     }
/// }
/// ```
#[macro_export]
macro_rules! tool_registry {
    (
        enum $enum_name:ident {
            $(
                $variant:ident($tool_name:literal, $description:literal) {
                    $(
                        $(#[$field_meta:meta])*
                        $field_name:ident : $field_type:ty
                    ),* $(,)?
                }
            ),* $(,)?
        }
    ) => {
        $(
            #[doc = concat!("Input parameters for the `", $tool_name, "` tool.")]
            #[derive(Debug, $crate::schemars::JsonSchema, $crate::serde::Deserialize)]
            #[schemars(crate = "::mercutio::schemars")]
            #[serde(crate = "::mercutio::serde")]
            pub struct $variant {
                $(
                    $(#[$field_meta])*
                    pub $field_name: $field_type,
                )*
            }

            impl $crate::ToolDef for $variant {
                const NAME: &'static str = $tool_name;
                const DESCRIPTION: &'static str = $description;
            }
        )*

        #[doc = concat!("Tool dispatch enum for this server.")]
        pub enum $enum_name {
            $(
                #[doc = concat!("The `", $tool_name, "` tool.")]
                $variant($variant),
            )*
        }

        impl $crate::ToolRegistry for $enum_name {
            fn parse(
                name: &str,
                arguments: $crate::serde_json::Value,
            ) -> std::result::Result<Self, $crate::JsonRpcError> {
                match name {
                    $(
                        $tool_name => {
                            let input: $variant = $crate::serde_json::from_value(arguments)
                                .map_err(|e| $crate::JsonRpcError::InvalidParams {
                                    msg: format!("{}: {}", $tool_name, e),
                                })?;
                            Ok(Self::$variant(input))
                        }
                    )*
                    _ => Err($crate::JsonRpcError::MethodNotFound {
                        msg: format!("unknown tool: {name}"),
                    }),
                }
            }

            fn definitions() -> $crate::ToolDefinitions {
                $crate::ToolDefinitions::new(vec![
                    $(
                        $crate::ToolDefinition::from_tool::<$variant>(),
                    )*
                ])
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::{IntoToolResponse, NoTools, ToolDefinition, ToolOutput, ToolRegistry};
    use crate::JsonRpcError;

    #[test]
    fn no_tools_definitions_empty() {
        assert!(NoTools::definitions().is_empty());
    }

    #[test]
    fn no_tools_parse_returns_error() {
        let result = NoTools::parse("anything", serde_json::Value::Null);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, JsonRpcError::MethodNotFound { .. }));
    }

    #[test]
    fn tool_definition_from_tool() {
        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct TestInput {
            value: String,
        }

        impl super::ToolDef for TestInput {
            const NAME: &'static str = "test_tool";
            const DESCRIPTION: &'static str = "A test tool";
        }

        let def = ToolDefinition::from_tool::<TestInput>();
        assert_eq!(def.name, "test_tool");
        assert_eq!(def.description, "A test tool");
        assert_eq!(def.input_schema.type_(), "object");
        assert!(def.input_schema.properties.is_some());
    }

    #[test]
    fn field_docstrings_become_schema_descriptions() {
        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct TestInput {
            /// The city to look up.
            city: String,
            /// Temperature unit preference.
            units: Option<String>,
        }

        impl super::ToolDef for TestInput {
            const NAME: &'static str = "test";
            const DESCRIPTION: &'static str = "Test";
        }

        let def = ToolDefinition::from_tool::<TestInput>();
        let props = def.input_schema.properties.expect("properties");
        let city_prop = props.get("city").expect("city property");
        let city_desc = city_prop.get("description").and_then(|v| v.as_str());
        assert_eq!(city_desc, Some("The city to look up."));

        let units_prop = props.get("units").expect("units property");
        let units_desc = units_prop.get("description").and_then(|v| v.as_str());
        assert_eq!(units_desc, Some("Temperature unit preference."));
    }

    #[test]
    fn tool_output_from_string() {
        let result = "hello".into_tool_response();
        let json = serde_json::to_value(&result).expect("serialize");
        let content = json.get("content").expect("content field");
        assert!(content.is_array());
        assert_eq!(content.as_array().expect("array").len(), 1);
        assert_eq!(json.get("isError").and_then(|v| v.as_bool()), Some(false));
    }

    #[test]
    fn tool_output_from_owned_string() {
        let result = String::from("hello").into_tool_response();
        let json = serde_json::to_value(&result).expect("serialize");
        let content = json.get("content").expect("content field");
        assert!(content.is_array());
    }

    #[test]
    fn tool_output_json_sets_structured_content() {
        #[derive(serde::Serialize)]
        struct Data {
            value: i32,
        }
        let result = ToolOutput::json(&Data { value: 42 }).into_tool_response();
        let json = serde_json::to_value(&result).expect("serialize");
        assert!(json.get("structuredContent").is_some());
        assert!(json.get("content").expect("content").is_array());
    }

    #[test]
    fn result_err_sets_is_error() {
        let result: Result<String, &str> = Err("something failed");
        let json = serde_json::to_value(&result.into_tool_response()).expect("serialize");
        assert_eq!(json.get("isError").and_then(|v| v.as_bool()), Some(true));
    }

    #[test]
    fn result_ok_sets_is_error_false() {
        let result: Result<&str, &str> = Ok("success");
        let json = serde_json::to_value(&result.into_tool_response()).expect("serialize");
        assert_eq!(json.get("isError").and_then(|v| v.as_bool()), Some(false));
    }

    #[test]
    fn tool_output_builder_multiple_text_blocks() {
        let result = ToolOutput::new()
            .text("first")
            .text("second")
            .into_tool_response();
        let json = serde_json::to_value(&result).expect("serialize");
        let content = json.get("content").expect("content");
        assert_eq!(content.as_array().expect("array").len(), 2);
    }

    #[test]
    fn tool_output_builder_text_and_structured() {
        #[derive(serde::Serialize)]
        struct Data {
            value: i32,
        }
        let result = ToolOutput::new()
            .text("summary")
            .structured(&Data { value: 1 })
            .into_tool_response();
        let json = serde_json::to_value(&result).expect("serialize");
        assert!(json.get("structuredContent").is_some());
        assert_eq!(
            json.get("content")
                .expect("content")
                .as_array()
                .expect("array")
                .len(),
            1
        );
    }

    #[test]
    fn tool_definition_display() {
        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct TestInput {
            /// The city to look up.
            city: String,
            /// Temperature unit preference.
            units: Option<String>,
        }

        impl super::ToolDef for TestInput {
            const NAME: &'static str = "get_weather";
            const DESCRIPTION: &'static str = "Gets weather for a city";
        }

        let def = ToolDefinition::from_tool::<TestInput>();
        insta::assert_snapshot!(def.to_string(), @r"
        ## get_weather

        Gets weather for a city

        Parameters:
          city (string, required)
            The city to look up.
          units (string, optional)
            Temperature unit preference.
        ");
    }

    #[test]
    fn tool_definition_schema_json() {
        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct TestInput {
            /// Required field.
            name: String,
            /// Optional field.
            count: Option<u32>,
        }

        impl super::ToolDef for TestInput {
            const NAME: &'static str = "test";
            const DESCRIPTION: &'static str = "Test tool";
        }

        let def = ToolDefinition::from_tool::<TestInput>();
        // Serialize via `Value` to convert HashMap to BTreeMap-backed Map for stable key order.
        let json = serde_json::to_value(&def.input_schema).expect("serialization failed");
        insta::assert_snapshot!(serde_json::to_string_pretty(&json).expect("formatting failed"), @r#"
        {
          "properties": {
            "count": {
              "description": "Optional field.",
              "format": "uint32",
              "minimum": 0.0,
              "type": "integer"
            },
            "name": {
              "description": "Required field.",
              "type": "string"
            }
          },
          "required": [
            "name"
          ],
          "type": "object"
        }
        "#);
    }

    #[test]
    fn tool_definitions_display() {
        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct GetWeather {
            /// City or address to look up.
            location: String,
        }

        impl super::ToolDef for GetWeather {
            const NAME: &'static str = "get_weather";
            const DESCRIPTION: &'static str = "Gets weather for a location";
        }

        #[allow(dead_code)]
        #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
        struct SetReminder {
            /// Reminder message.
            message: String,
            /// Minutes from now.
            delay_minutes: u32,
        }

        impl super::ToolDef for SetReminder {
            const NAME: &'static str = "set_reminder";
            const DESCRIPTION: &'static str = "Sets a reminder";
        }

        let defs = super::ToolDefinitions::new(vec![
            ToolDefinition::from_tool::<GetWeather>(),
            ToolDefinition::from_tool::<SetReminder>(),
        ]);
        insta::assert_snapshot!(defs.to_string(), @r"
        # Tools

        ## get_weather

        Gets weather for a location

        Parameters:
          location (string, required)
            City or address to look up.

        ## set_reminder

        Sets a reminder

        Parameters:
          delay_minutes (integer, required)
            Minutes from now.
          message (string, required)
            Reminder message.
        ");
    }

    #[test]
    fn tool_output_display_text() {
        let output = ToolOutput::new()
            .text("Temperature: 72F")
            .text("Conditions: Sunny");
        insta::assert_snapshot!(output.to_string(), @r"
        Temperature: 72F

        Conditions: Sunny
        ");
    }

    #[test]
    fn tool_output_display_with_structured() {
        #[derive(serde::Serialize)]
        struct Weather {
            temp: i32,
            conditions: String,
        }

        let output = ToolOutput::new()
            .text("Current weather")
            .structured(&Weather {
                temp: 72,
                conditions: "Sunny".into(),
            });
        insta::assert_snapshot!(output.to_string(), @r#"
        Current weather

        Structured Content:
        {
          "conditions": "Sunny",
          "temp": 72
        }
        "#);
    }

    #[test]
    fn tool_output_image_block() {
        let png_data = b"\x89PNG\r\n\x1a\n";
        let output = ToolOutput::new().image(png_data, "image/png");
        insta::assert_snapshot!(output.to_string(), @"[Image: image/png, 12 bytes]");
    }

    #[test]
    fn tool_output_audio_block() {
        let wav_header = b"RIFF\x00\x00\x00\x00WAVEfmt ";
        let output = ToolOutput::new().audio(wav_header, "audio/wav");
        insta::assert_snapshot!(output.to_string(), @"[Audio: audio/wav, 24 bytes]");
    }

    #[test]
    fn with_source_formats_error_chain() {
        use std::fmt;

        #[derive(Debug)]
        struct OuterError(InnerError);

        impl fmt::Display for OuterError {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "outer error")
            }
        }

        impl std::error::Error for OuterError {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                Some(&self.0)
            }
        }

        #[derive(Debug)]
        struct InnerError;

        impl fmt::Display for InnerError {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "inner cause")
            }
        }

        impl std::error::Error for InnerError {}

        let wrapped = super::WithSource(OuterError(InnerError));
        assert_eq!(wrapped.to_string(), "outer error: inner cause");
    }
}