turbomcp-protocol 3.0.9

Complete MCP protocol implementation with types, traits, context management, and message handling
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
//! Types for the MCP tool-calling system.
//!
//! This module defines the data structures for defining tools, their input/output schemas,
//! and the requests and responses used to list and execute them, as specified by the MCP standard.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::{content::ContentBlock, core::Cursor};

/// Optional metadata hints about a tool's behavior.
///
/// **Critical Warning** (from MCP spec):
/// > "All properties in ToolAnnotations are **hints**. They are not guaranteed to
/// > provide a faithful description of tool behavior. **Clients should never make
/// > tool use decisions based on ToolAnnotations received from untrusted servers.**"
///
/// These fields are useful for UI display and general guidance, but should never
/// be trusted for security decisions or behavioral assumptions.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolAnnotations {
    /// A user-friendly title for display in UIs (hint only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Role-based audience hint. Per spec, should be `"user"` or `"assistant"` (hint only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audience: Option<Vec<String>>,
    /// Subjective priority for UI sorting (hint only, often ignored).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<f64>,
    /// **Hint** that the tool may perform destructive actions (e.g., deleting data).
    ///
    /// Do not trust this for security decisions. Default: `true` if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "destructiveHint")]
    pub destructive_hint: Option<bool>,
    /// **Hint** that repeated calls with same args have no additional effects.
    ///
    /// Useful for retry logic, but verify actual behavior. Default: `false` if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "idempotentHint")]
    pub idempotent_hint: Option<bool>,
    /// **Hint** that the tool may interact with external systems or the real world.
    ///
    /// Do not trust this for sandboxing decisions. Default: `true` if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "openWorldHint")]
    pub open_world_hint: Option<bool>,
    /// **Hint** that the tool does not modify state (read-only).
    ///
    /// Do not trust this for security decisions. Default: `false` if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "readOnlyHint")]
    pub read_only_hint: Option<bool>,

    /// **Hint** for task augmentation support (MCP 2025-11-25 draft, SEP-1686)
    ///
    /// Indicates whether this tool supports task-augmented invocation:
    /// - `never` (default): Tool MUST NOT be invoked as a task
    /// - `optional`: Tool MAY be invoked as a task or normal request
    /// - `always`: Tool SHOULD be invoked as a task (server may reject non-task calls)
    ///
    /// This is a **hint** and does not guarantee behavioral conformance.
    ///
    /// ## Capability Requirements
    ///
    /// If `tasks.requests.tools.call` capability is false, clients MUST ignore this hint.
    /// If capability is true:
    /// - `taskHint` absent or `"never"`: MUST NOT invoke as task
    /// - `taskHint: "optional"`: MAY invoke as task
    /// - `taskHint: "always"`: SHOULD invoke as task
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "taskHint")]
    pub task_hint: Option<TaskHint>,

    /// Custom application-specific hints.
    #[serde(flatten)]
    pub custom: HashMap<String, serde_json::Value>,
}

/// Task hint for tool invocation (MCP 2025-11-25 draft, SEP-1686)
///
/// Indicates how a tool should be invoked with respect to task augmentation.
/// Note: This is kept for backward compatibility. The newer API uses
/// `ToolExecution.task_support` with `TaskSupportMode`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum TaskHint {
    /// Tool MUST NOT be invoked as a task (default behavior)
    Never,
    /// Tool MAY be invoked as either a task or normal request
    Optional,
    /// Tool SHOULD be invoked as a task (server may reject non-task calls)
    Always,
}

/// Task support mode for tool execution (MCP 2025-11-25)
///
/// Indicates whether this tool supports task-augmented execution.
/// This allows clients to handle long-running operations through polling
/// the task system.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "lowercase")]
pub enum TaskSupportMode {
    /// Tool does not support task-augmented execution (default when absent)
    #[default]
    Forbidden,
    /// Tool may support task-augmented execution
    Optional,
    /// Tool requires task-augmented execution
    Required,
}

/// Execution-related properties for a tool (MCP 2025-11-25)
///
/// Contains execution configuration hints for tools, particularly around
/// task-augmented execution support.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolExecution {
    /// Indicates whether this tool supports task-augmented execution.
    ///
    /// - `forbidden` (default): Tool does not support task-augmented execution
    /// - `optional`: Tool may support task-augmented execution
    /// - `required`: Tool requires task-augmented execution
    #[serde(rename = "taskSupport", skip_serializing_if = "Option::is_none")]
    pub task_support: Option<TaskSupportMode>,
}

/// Represents a tool that can be executed by an MCP server
///
/// A `Tool` definition includes its programmatic name, a human-readable description,
/// and JSON schemas for its inputs and outputs.
///
/// ## Version Support
/// - MCP 2025-11-25: name, title, description, inputSchema, outputSchema, annotations, _meta
/// - MCP 2025-11-25 draft (SEP-973): + icons
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tool {
    /// The programmatic name of the tool, used to identify it in `CallToolRequest`.
    pub name: String,

    /// An optional, user-friendly title for the tool. Display name precedence is: `title`, `annotations.title`, then `name`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// A human-readable description of what the tool does, which can be used by clients or LLMs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// The JSON Schema object defining the parameters the tool accepts.
    #[serde(rename = "inputSchema")]
    pub input_schema: ToolInputSchema,

    /// An optional JSON Schema object defining the structure of the tool's successful output.
    #[serde(rename = "outputSchema", skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<ToolOutputSchema>,

    /// Execution-related properties for this tool (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution: Option<ToolExecution>,

    /// Optional, additional metadata providing hints about the tool's behavior.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<ToolAnnotations>,

    /// Optional set of icons for UI display (MCP 2025-11-25 draft, SEP-973)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<super::core::Icon>>,

    /// A general-purpose metadata field for custom data.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

impl Default for Tool {
    fn default() -> Self {
        Self {
            name: "unnamed_tool".to_string(), // Must have a valid name for MCP compliance
            title: None,
            description: None,
            input_schema: ToolInputSchema::default(),
            output_schema: None,
            execution: None,
            annotations: None,
            icons: None,
            meta: None,
        }
    }
}

impl Tool {
    /// Creates a new `Tool` with a given name.
    ///
    /// # Panics
    /// Panics if the name is empty or contains only whitespace.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        assert!(!name.trim().is_empty(), "Tool name cannot be empty");
        Self {
            name,
            title: None,
            description: None,
            input_schema: ToolInputSchema::default(),
            output_schema: None,
            execution: None,
            annotations: None,
            icons: None,
            meta: None,
        }
    }

    /// Creates a new `Tool` with a name and a description.
    ///
    /// # Panics
    /// Panics if the name is empty or contains only whitespace.
    pub fn with_description(name: impl Into<String>, description: impl Into<String>) -> Self {
        let name = name.into();
        assert!(!name.trim().is_empty(), "Tool name cannot be empty");
        Self {
            name,
            title: None,
            description: Some(description.into()),
            input_schema: ToolInputSchema::default(),
            output_schema: None,
            execution: None,
            annotations: None,
            icons: None,
            meta: None,
        }
    }

    /// Sets the execution properties for this tool.
    pub fn with_execution(mut self, execution: ToolExecution) -> Self {
        self.execution = Some(execution);
        self
    }

    /// Sets the input schema for this tool.
    ///
    /// # Example
    /// ```
    /// # use turbomcp_protocol::types::{Tool, ToolInputSchema};
    /// let schema = ToolInputSchema::empty();
    /// let tool = Tool::new("my_tool").with_input_schema(schema);
    /// ```
    pub fn with_input_schema(mut self, schema: ToolInputSchema) -> Self {
        self.input_schema = schema;
        self
    }

    /// Sets the output schema for this tool.
    pub fn with_output_schema(mut self, schema: ToolOutputSchema) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Sets the user-friendly title for this tool.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the annotations for this tool.
    pub fn with_annotations(mut self, annotations: ToolAnnotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

/// Defines the structure of the arguments a tool accepts, as a JSON Schema object.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInputSchema {
    /// The type of the schema, which must be "object" for tool inputs.
    #[serde(rename = "type")]
    pub schema_type: String,
    /// A map defining the properties (parameters) the tool accepts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, serde_json::Value>>,
    /// A list of property names that are required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    /// Whether additional, unspecified properties are allowed.
    #[serde(
        rename = "additionalProperties",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_properties: Option<bool>,
}

impl Default for ToolInputSchema {
    /// Creates a default `ToolInputSchema` that accepts an empty object.
    fn default() -> Self {
        Self {
            schema_type: "object".to_string(),
            properties: None,
            required: None,
            additional_properties: None,
        }
    }
}

impl ToolInputSchema {
    /// Creates a new, empty input schema that accepts no parameters.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Creates a new schema with a given set of properties.
    pub fn with_properties(properties: HashMap<String, serde_json::Value>) -> Self {
        Self {
            schema_type: "object".to_string(),
            properties: Some(properties),
            required: None,
            additional_properties: None,
        }
    }

    /// Creates a new schema with a given set of properties and a list of required properties.
    pub fn with_required_properties(
        properties: HashMap<String, serde_json::Value>,
        required: Vec<String>,
    ) -> Self {
        Self {
            schema_type: "object".to_string(),
            properties: Some(properties),
            required: Some(required),
            additional_properties: Some(false),
        }
    }

    /// Adds a property to the schema using a builder pattern.
    ///
    /// # Example
    /// ```
    /// # use turbomcp_protocol::types::ToolInputSchema;
    /// # use serde_json::json;
    /// let schema = ToolInputSchema::empty()
    ///     .add_property("name".to_string(), json!({ "type": "string" }));
    /// ```
    pub fn add_property(mut self, name: String, property: serde_json::Value) -> Self {
        self.properties
            .get_or_insert_with(HashMap::new)
            .insert(name, property);
        self
    }

    /// Marks a property as required using a builder pattern.
    ///
    /// # Example
    /// ```
    /// # use turbomcp_protocol::types::ToolInputSchema;
    /// # use serde_json::json;
    /// let schema = ToolInputSchema::empty()
    ///     .add_property("name".to_string(), json!({ "type": "string" }))
    ///     .require_property("name".to_string());
    /// ```
    pub fn require_property(mut self, name: String) -> Self {
        let required = self.required.get_or_insert_with(Vec::new);
        if !required.contains(&name) {
            required.push(name);
        }
        self
    }
}

/// Defines the structure of a tool's successful output, as a JSON Schema object.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolOutputSchema {
    /// The type of the schema, which must be "object" for tool outputs.
    #[serde(rename = "type")]
    pub schema_type: String,
    /// A map defining the properties of the output object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, serde_json::Value>>,
    /// A list of property names in the output that are required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    /// Whether additional, unspecified properties are allowed in the output.
    #[serde(
        rename = "additionalProperties",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_properties: Option<bool>,
}

/// A request to list the available tools on a server.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListToolsRequest {
    /// An optional cursor for pagination. If provided, the server should return
    /// the next page of results starting after this cursor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<Cursor>,
    /// Optional metadata for the request.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub _meta: Option<serde_json::Value>,
}

/// The result of a `ListToolsRequest`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListToolsResult {
    /// The list of available tools for the current page.
    pub tools: Vec<Tool>,
    /// An optional continuation token for retrieving the next page of results.
    /// If `None`, there are no more results.
    #[serde(rename = "nextCursor", skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<Cursor>,
    /// Optional metadata for the result.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub _meta: Option<serde_json::Value>,
}

/// A request to execute a specific tool.
///
/// ## Version Support
/// - MCP 2025-11-25: name, arguments, _meta
/// - MCP 2025-11-25 draft (SEP-1686): + task (optional task augmentation)
///
/// ## Task Augmentation
///
/// When the `task` field is present, the receiver responds immediately with
/// a `CreateTaskResult` containing a task ID. The actual tool result is available
/// later via `tasks/result`.
///
/// ```rust,ignore
/// use turbomcp_protocol::types::{CallToolRequest, tasks::TaskMetadata};
///
/// let request = CallToolRequest {
///     name: "long_running_tool".to_string(),
///     arguments: Some(json!({"data": "value"})),
///     task: Some(TaskMetadata { ttl: Some(300_000) }), // 5 minute lifetime
///     _meta: None,
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CallToolRequest {
    /// The programmatic name of the tool to call.
    pub name: String,

    /// The arguments to pass to the tool, conforming to its `input_schema`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<HashMap<String, serde_json::Value>>,

    /// Optional task metadata for task-augmented requests (MCP 2025-11-25 draft)
    ///
    /// When present, this request will be executed asynchronously and the receiver
    /// will respond immediately with a `CreateTaskResult`. The actual tool result
    /// is available later via `tasks/result`.
    ///
    /// Requires:
    /// - Server capability: `tasks.requests.tools.call`
    /// - Tool annotation: `taskHint` must be "optional" or "always" (or absent/"never" for default)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task: Option<crate::types::tasks::TaskMetadata>,

    /// Optional metadata for the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub _meta: Option<serde_json::Value>,
}

/// The result of a `CallToolRequest`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CallToolResult {
    /// The output of the tool, typically as a series of text or other content blocks. This is required.
    pub content: Vec<ContentBlock>,
    /// An optional boolean indicating whether the tool execution resulted in an error.
    ///
    /// When `is_error` is `true`, all content blocks should be treated as error information.
    /// The error message may span multiple text blocks for structured error reporting.
    #[serde(rename = "isError", skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
    /// Optional structured output from the tool, conforming to its `output_schema`.
    ///
    /// When present, this contains schema-validated JSON output that clients can parse
    /// and use programmatically. Tools that return structured content SHOULD also include
    /// the serialized JSON in a TextContent block for backward compatibility with clients
    /// that don't support structured output.
    ///
    /// See [`Tool::output_schema`] for defining the expected structure.
    #[serde(rename = "structuredContent", skip_serializing_if = "Option::is_none")]
    pub structured_content: Option<serde_json::Value>,
    /// Optional metadata for the result.
    ///
    /// This field is for client applications and tools to pass additional context that
    /// should NOT be exposed to LLMs. Examples include tracking IDs, performance metrics,
    /// cache status, or internal state information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub _meta: Option<serde_json::Value>,
    /// Optional task ID when tool execution is augmented with task tracking (MCP 2025-11-25 draft - SEP-1686).
    ///
    /// When a tool call includes task metadata, the server creates a task to track the operation
    /// and returns the task_id here. Clients can use this to monitor progress via tasks/get
    /// or retrieve final results via tasks/result.
    #[serde(rename = "taskId", skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
}

impl CallToolResult {
    /// Extracts and concatenates all text content from the result.
    ///
    /// This is useful for simple text-only tools or when you want to present
    /// all textual output as a single string.
    ///
    /// # Returns
    ///
    /// A single string containing all text blocks concatenated with newlines.
    /// Returns an empty string if there are no text blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_protocol::types::{CallToolResult, ContentBlock, TextContent};
    ///
    /// let result = CallToolResult {
    ///     content: vec![
    ///         ContentBlock::Text(TextContent {
    ///             text: "Line 1".to_string(),
    ///             annotations: None,
    ///             meta: None,
    ///         }),
    ///         ContentBlock::Text(TextContent {
    ///             text: "Line 2".to_string(),
    ///             annotations: None,
    ///             meta: None,
    ///         }),
    ///     ],
    ///     is_error: None,
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    ///
    /// assert_eq!(result.all_text(), "Line 1\nLine 2");
    /// ```
    pub fn all_text(&self) -> String {
        self.content
            .iter()
            .filter_map(|block| match block {
                ContentBlock::Text(text) => Some(text.text.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Returns the text content of the first text block, if any.
    ///
    /// This is a common pattern for simple tools that return a single text response.
    ///
    /// # Returns
    ///
    /// `Some(&str)` if the first content block is text, `None` otherwise.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_protocol::types::{CallToolResult, ContentBlock, TextContent};
    ///
    /// let result = CallToolResult {
    ///     content: vec![
    ///         ContentBlock::Text(TextContent {
    ///             text: "Hello, world!".to_string(),
    ///             annotations: None,
    ///             meta: None,
    ///         }),
    ///     ],
    ///     is_error: None,
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    ///
    /// assert_eq!(result.first_text(), Some("Hello, world!"));
    /// ```
    pub fn first_text(&self) -> Option<&str> {
        self.content.first().and_then(|block| match block {
            ContentBlock::Text(text) => Some(text.text.as_str()),
            _ => None,
        })
    }

    /// Checks if the tool execution resulted in an error.
    ///
    /// # Returns
    ///
    /// `true` if `is_error` is explicitly set to `true`, `false` otherwise
    /// (including when `is_error` is `None`).
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_protocol::types::CallToolResult;
    ///
    /// let success_result = CallToolResult {
    ///     content: vec![],
    ///     is_error: Some(false),
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    /// assert!(!success_result.has_error());
    ///
    /// let error_result = CallToolResult {
    ///     content: vec![],
    ///     is_error: Some(true),
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    /// assert!(error_result.has_error());
    ///
    /// let unspecified_result = CallToolResult {
    ///     content: vec![],
    ///     is_error: None,
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    /// assert!(!unspecified_result.has_error());
    /// ```
    pub fn has_error(&self) -> bool {
        self.is_error.unwrap_or(false)
    }

    /// Creates a user-friendly display string for the tool result.
    ///
    /// This method provides a formatted representation suitable for logging,
    /// debugging, or displaying to end users. It handles multiple content types
    /// and includes structured content and error information when present.
    ///
    /// # Returns
    ///
    /// A formatted string representing the tool result.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_protocol::types::{CallToolResult, ContentBlock, TextContent};
    ///
    /// let result = CallToolResult {
    ///     content: vec![
    ///         ContentBlock::Text(TextContent {
    ///             text: "Operation completed".to_string(),
    ///             annotations: None,
    ///             meta: None,
    ///         }),
    ///     ],
    ///     is_error: Some(false),
    ///     structured_content: None,
    ///     _meta: None,
    ///     task_id: None,
    /// };
    ///
    /// let display = result.to_display_string();
    /// assert!(display.contains("Operation completed"));
    /// ```
    pub fn to_display_string(&self) -> String {
        let mut parts = Vec::new();

        // Add error indicator if present
        if self.has_error() {
            parts.push("ERROR:".to_string());
        }

        // Process content blocks
        for (i, block) in self.content.iter().enumerate() {
            match block {
                ContentBlock::Text(text) => {
                    parts.push(text.text.clone());
                }
                ContentBlock::Image(img) => {
                    parts.push(format!(
                        "[Image: {} bytes, type: {}]",
                        img.data.len(),
                        img.mime_type
                    ));
                }
                ContentBlock::Audio(audio) => {
                    parts.push(format!(
                        "[Audio: {} bytes, type: {}]",
                        audio.data.len(),
                        audio.mime_type
                    ));
                }
                ContentBlock::ResourceLink(link) => {
                    let desc = link.description.as_deref().unwrap_or("");
                    let mime = link
                        .mime_type
                        .as_deref()
                        .map(|m| format!(" [{}]", m))
                        .unwrap_or_default();
                    parts.push(format!(
                        "[Resource: {}{}{}{}]",
                        link.name,
                        mime,
                        if !desc.is_empty() { ": " } else { "" },
                        desc
                    ));
                }
                ContentBlock::Resource(_resource) => {
                    parts.push(format!("[Embedded Resource #{}]", i + 1));
                }
                ContentBlock::ToolUse(tool_use) => {
                    parts.push(format!(
                        "[Tool Use: {} (id: {})]",
                        tool_use.name, tool_use.id
                    ));
                }
                ContentBlock::ToolResult(tool_result) => {
                    parts.push(format!(
                        "[Tool Result for: {}{}]",
                        tool_result.tool_use_id,
                        if tool_result.is_error.unwrap_or(false) {
                            " (ERROR)"
                        } else {
                            ""
                        }
                    ));
                }
            }
        }

        // Add structured content indicator if present
        if self.structured_content.is_some() {
            parts.push("[Includes structured output]".to_string());
        }

        parts.join("\n")
    }
}

// =============================================================================
// Conversions from turbomcp-core types (for unified handler support)
// =============================================================================
//
// These conversions enable the unified IntoToolResponse pattern, allowing
// handlers to return core types that are automatically converted to protocol types.
//
// IMPORTANT NOTES:
// - HashMap conversion: O(n) overhead due to hashbrown→std HashMap conversion
// - Lossy conversion: Protocol's `structured_content` and `task_id` fields are
//   NOT present in core types, so round-trip (protocol→core→protocol) loses them
// - Resource fallback: Empty text is used if ResourceContent has neither text nor blob

/// Convert core Annotations to protocol Annotations.
///
/// Note: Incurs O(n) conversion overhead from `hashbrown::HashMap` to `std::collections::HashMap`.
impl From<turbomcp_core::types::core::Annotations> for super::Annotations {
    fn from(core_ann: turbomcp_core::types::core::Annotations) -> Self {
        // Convert hashbrown::HashMap to std::collections::HashMap
        // Both implementations guarantee unique keys, so no data loss occurs
        let custom: std::collections::HashMap<String, serde_json::Value> =
            core_ann.custom.into_iter().collect();
        Self {
            audience: core_ann.audience,
            priority: core_ann.priority,
            last_modified: core_ann.last_modified,
            custom,
        }
    }
}

/// Convert core Content to protocol ContentBlock
impl From<turbomcp_core::types::content::Content> for super::ContentBlock {
    fn from(content: turbomcp_core::types::content::Content) -> Self {
        use turbomcp_core::types::content::Content as CoreContent;
        match content {
            CoreContent::Text { text, annotations } => {
                super::ContentBlock::Text(super::TextContent {
                    text,
                    annotations: annotations.map(Into::into),
                    meta: None,
                })
            }
            CoreContent::Image {
                data,
                mime_type,
                annotations,
            } => super::ContentBlock::Image(super::ImageContent {
                data: data.into(),
                mime_type: mime_type.to_string().into(),
                annotations: annotations.map(Into::into),
                meta: None,
            }),
            CoreContent::Audio {
                data,
                mime_type,
                annotations,
            } => super::ContentBlock::Audio(super::AudioContent {
                data: data.into(),
                mime_type: mime_type.to_string().into(),
                annotations: annotations.map(Into::into),
                meta: None,
            }),
            CoreContent::Resource {
                resource,
                annotations,
            } => {
                // Convert core ResourceContent to protocol EmbeddedResource
                // Core uses a flat struct with optional text/blob, protocol uses an enum
                let protocol_resource = if let Some(text) = resource.text {
                    super::ResourceContent::Text(super::TextResourceContents {
                        uri: resource.uri.to_string().into(),
                        mime_type: resource.mime_type.map(|mime| mime.to_string().into()),
                        text,
                        meta: None,
                    })
                } else if let Some(blob) = resource.blob {
                    super::ResourceContent::Blob(super::BlobResourceContents {
                        uri: resource.uri.to_string().into(),
                        mime_type: resource.mime_type.map(|mime| mime.to_string().into()),
                        blob: blob.into(),
                        meta: None,
                    })
                } else {
                    // Default to empty text if neither is set.
                    // NOTE: This is a fallback for malformed core resources - callers should
                    // ensure ResourceContent has either text or blob set.
                    #[cfg(feature = "std")]
                    eprintln!(
                        "[turbomcp-protocol] WARNING: Resource '{}' has neither text nor blob content",
                        resource.uri
                    );
                    super::ResourceContent::Text(super::TextResourceContents {
                        uri: resource.uri.to_string().into(),
                        mime_type: resource.mime_type.map(|mime| mime.to_string().into()),
                        text: String::new(),
                        meta: None,
                    })
                };
                super::ContentBlock::Resource(super::EmbeddedResource {
                    resource: protocol_resource,
                    annotations: annotations.map(Into::into),
                    meta: None,
                })
            }
        }
    }
}

/// Convert core CallToolResult to protocol CallToolResult
///
/// This enables the unified IntoToolResponse pattern for native handlers.
///
/// **Note**: `structured_content` and `task_id` fields are set to `None` since
/// core types don't have these fields. Round-trip conversion (protocol→core→protocol)
/// will lose these values.
impl From<turbomcp_core::types::tools::CallToolResult> for CallToolResult {
    fn from(core_result: turbomcp_core::types::tools::CallToolResult) -> Self {
        Self {
            content: core_result.content.into_iter().map(Into::into).collect(),
            is_error: core_result.is_error,
            structured_content: None,
            _meta: core_result._meta,
            task_id: None,
        }
    }
}

#[cfg(test)]
mod conversion_tests {
    use super::*;
    use turbomcp_core::types::content::Content as CoreContent;
    use turbomcp_core::types::tools::CallToolResult as CoreCallToolResult;

    #[test]
    fn test_core_content_to_protocol_text() {
        let core = CoreContent::text("hello world");
        let protocol: ContentBlock = core.into();

        match protocol {
            ContentBlock::Text(text) => {
                assert_eq!(text.text, "hello world");
                assert!(text.annotations.is_none());
            }
            _ => panic!("Expected Text variant"),
        }
    }

    #[test]
    fn test_core_content_to_protocol_image() {
        let core = CoreContent::image("base64data", "image/png");
        let protocol: ContentBlock = core.into();

        match protocol {
            ContentBlock::Image(img) => {
                assert_eq!(img.data, "base64data");
                assert_eq!(img.mime_type, "image/png");
            }
            _ => panic!("Expected Image variant"),
        }
    }

    #[test]
    fn test_core_call_tool_result_to_protocol() {
        let core = CoreCallToolResult::text("success");
        let protocol: CallToolResult = core.into();

        assert_eq!(protocol.content.len(), 1);
        assert!(protocol.is_error.is_none());
        assert!(protocol.structured_content.is_none());
        assert!(protocol.task_id.is_none());

        match &protocol.content[0] {
            ContentBlock::Text(text) => assert_eq!(text.text, "success"),
            _ => panic!("Expected Text content"),
        }
    }

    #[test]
    fn test_core_call_tool_result_error_preserved() {
        let core = CoreCallToolResult::error("something failed");
        let protocol: CallToolResult = core.into();

        assert_eq!(protocol.is_error, Some(true));
        match &protocol.content[0] {
            ContentBlock::Text(text) => assert_eq!(text.text, "something failed"),
            _ => panic!("Expected Text content"),
        }
    }

    #[test]
    fn test_annotations_conversion() {
        use crate::types::Annotations;
        use turbomcp_core::types::core::Annotations as CoreAnnotations;

        // Create core annotations (custom field uses Default for simplicity)
        let core = CoreAnnotations {
            audience: Some(vec!["user".to_string(), "assistant".to_string()]),
            priority: Some(0.75),
            last_modified: Some("2025-01-13T12:00:00Z".to_string()),
            custom: Default::default(),
        };

        let protocol: Annotations = core.into();

        // Verify all fields are correctly converted
        assert_eq!(
            protocol.audience,
            Some(vec!["user".to_string(), "assistant".to_string()])
        );
        assert_eq!(protocol.priority, Some(0.75));
        assert_eq!(
            protocol.last_modified,
            Some("2025-01-13T12:00:00Z".to_string())
        );
        assert!(protocol.custom.is_empty());
    }
}