component-shape-mcp 0.3.0

Shared MCP protocol and schema helpers for component-shape integrations.
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
use super::*;

/// A clonable collection of MCP tool definitions and in-process handlers.
///
/// Resources, prompts, server identity, and transport lifecycle remain owned
/// by [`McpServer`].
#[derive(Clone, Default)]
pub struct McpToolRegistry {
    tools: BTreeMap<String, Arc<dyn ToolExecutor>>,
}

impl McpToolRegistry {
    /// Create an empty tool registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a synchronous MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_tool<Call>(
        &mut self,
        definition: ToolDefinition,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Call: Fn(McpToolCall) -> ToolCallResult + Send + Sync + 'static,
    {
        let name = definition.name.to_string();
        validate_tool_definition(&definition)?;
        if self.tools.contains_key(&name) {
            return Err(McpToolError::duplicate_tool(name));
        }

        self.tools.insert(
            name,
            Arc::new(RegisteredTool {
                definition,
                call: Arc::new(move |arguments| Box::pin(std::future::ready(call(arguments)))),
            }),
        );
        Ok(())
    }

    /// Register a synchronous typed MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_typed_tool<Input, Call>(
        &mut self,
        definition: McpTypedTool<Input>,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Input: McpToolInput,
        Call: Fn(Input) -> ToolCallResult + Send + Sync + 'static,
    {
        self.add_tool(definition.into_definition(), move |tool_call| {
            let input = match Input::from_tool_call(tool_call) {
                Ok(input) => input,
                Err(error) => return tool_error_result_for(error),
            };
            call(input)
        })
    }

    /// Register an async MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_tool_async<Call, Fut>(
        &mut self,
        definition: ToolDefinition,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Call: Fn(McpToolCall) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        let name = definition.name.to_string();
        validate_tool_definition(&definition)?;
        if self.tools.contains_key(&name) {
            return Err(McpToolError::duplicate_tool(name));
        }

        self.tools.insert(
            name,
            Arc::new(RegisteredTool {
                definition,
                call: Arc::new(move |arguments| Box::pin(call(arguments))),
            }),
        );
        Ok(())
    }

    /// Register an async typed MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_typed_tool_async<Input, Call, Fut>(
        &mut self,
        definition: McpTypedTool<Input>,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Input: McpToolInput,
        Call: Fn(Input) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        self.add_tool_async(definition.into_definition(), move |tool_call| {
            let input = Input::from_tool_call(tool_call);
            let future = match input {
                Ok(input) => call(input),
                Err(error) => {
                    return Box::pin(std::future::ready(tool_error_result_for(error)))
                        as ToolFuture;
                },
            };
            Box::pin(future) as ToolFuture
        })
    }

    /// Return registered MCP tool definitions.
    #[must_use]
    pub fn list_tools(&self) -> Vec<ToolDefinition> {
        self.tools
            .values()
            .map(|executor| executor.definition())
            .collect()
    }

    /// Whether a tool name is already registered.
    #[must_use]
    pub fn contains_tool(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Number of registered tools.
    #[must_use]
    pub fn tool_count(&self) -> usize {
        self.tools.len()
    }

    /// Calls a registered tool and converts validation or handler failures into
    /// a protocol-level tool result.
    #[must_use]
    pub fn call_tool(&self, name: &str, arguments: Option<Value>) -> ToolCallResult {
        let call = match McpToolCall::from_value(arguments) {
            Ok(call) => call,
            Err(error) => return tool_error_result_for(error),
        };
        let (definition, call) = match self.resolve_tool(name, call) {
            Ok(resolved) => resolved,
            Err(error) => return tool_error_result_for(error),
        };
        validate_tool_call_result(
            name,
            definition.output_schema.as_deref(),
            block_on_tool_future(call),
        )
    }

    /// Asynchronously calls a registered tool and converts validation or
    /// handler failures into a protocol-level tool result.
    pub async fn call_tool_async(&self, name: &str, arguments: Option<Value>) -> ToolCallResult {
        let call = match McpToolCall::from_value(arguments) {
            Ok(call) => call,
            Err(error) => return tool_error_result_for(error),
        };
        let (definition, call) = match self.resolve_tool(name, call) {
            Ok(resolved) => resolved,
            Err(error) => return tool_error_result_for(error),
        };
        validate_tool_call_result(name, definition.output_schema.as_deref(), call.await)
    }

    fn definition(&self, name: &str) -> Option<ToolDefinition> {
        self.tools.get(name).map(|executor| executor.definition())
    }

    fn resolve_tool(
        &self,
        name: &str,
        call: McpToolCall,
    ) -> Result<(ToolDefinition, ToolFuture), McpToolError> {
        match self.tools.get(name) {
            Some(executor) => Ok((executor.definition(), executor.call(call))),
            None => Err(McpToolError::UnknownTool {
                name: name.to_string(),
            }),
        }
    }
}

/// In-process MCP server that owns registered tools, resources, and prompts.
#[derive(Clone)]
pub struct McpServer {
    pub(crate) server_name: Cow<'static, str>,
    pub(crate) server_version: Cow<'static, str>,
    tools: McpToolRegistry,
    resources: BTreeMap<String, Arc<dyn ResourceReader>>,
    resource_templates: Vec<ResourceTemplate>,
    prompts: BTreeMap<String, Arc<dyn PromptExecutor>>,
}

impl McpServer {
    /// Create a dynamic MCP tool server with the advertised metadata.
    pub fn new(
        server_name: impl Into<Cow<'static, str>>,
        server_version: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            server_name: server_name.into(),
            server_version: server_version.into(),
            tools: McpToolRegistry::new(),
            resources: BTreeMap::new(),
            resource_templates: Vec::new(),
            prompts: BTreeMap::new(),
        }
    }

    /// Start building a dynamic MCP tool server with generated registrars.
    pub fn builder(
        server_name: impl Into<Cow<'static, str>>,
        server_version: impl Into<Cow<'static, str>>,
    ) -> McpServerBuilder {
        McpServerBuilder::new(server_name, server_version)
    }

    /// Create a dynamic MCP server from an existing tool registry.
    #[must_use]
    pub fn from_tool_registry(
        server_name: impl Into<Cow<'static, str>>,
        server_version: impl Into<Cow<'static, str>>,
        tools: McpToolRegistry,
    ) -> Self {
        Self {
            tools,
            ..Self::new(server_name, server_version)
        }
    }

    /// Borrow the shared tool registry.
    #[must_use]
    pub fn tool_registry(&self) -> &McpToolRegistry {
        &self.tools
    }

    /// Mutably borrow the shared tool registry.
    pub fn tool_registry_mut(&mut self) -> &mut McpToolRegistry {
        &mut self.tools
    }

    /// Consume the server and return its tool registry.
    #[must_use]
    pub fn into_tool_registry(self) -> McpToolRegistry {
        self.tools
    }

    /// Register a synchronous MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_tool<Call>(
        &mut self,
        definition: ToolDefinition,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Call: Fn(McpToolCall) -> ToolCallResult + Send + Sync + 'static,
    {
        self.tools.add_tool(definition, call)
    }

    /// Register a synchronous typed MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_typed_tool<Input, Call>(
        &mut self,
        definition: McpTypedTool<Input>,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Input: McpToolInput,
        Call: Fn(Input) -> ToolCallResult + Send + Sync + 'static,
    {
        self.tools.add_typed_tool(definition, call)
    }

    /// Register an async MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_tool_async<Call, Fut>(
        &mut self,
        definition: ToolDefinition,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Call: Fn(McpToolCall) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        self.tools.add_tool_async(definition, call)
    }

    /// Register an async typed MCP tool handler.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a tool with the
    /// same name is already registered.
    pub fn add_typed_tool_async<Input, Call, Fut>(
        &mut self,
        definition: McpTypedTool<Input>,
        call: Call,
    ) -> Result<(), McpToolError>
    where
        Input: McpToolInput,
        Call: Fn(Input) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        self.tools.add_typed_tool_async(definition, call)
    }

    /// Return registered MCP tool definitions.
    #[must_use]
    pub fn list_tools(&self) -> Vec<ToolDefinition> {
        self.tools.list_tools()
    }

    /// Whether a tool name is already registered.
    #[must_use]
    pub fn contains_tool(&self, name: &str) -> bool {
        self.tools.contains_tool(name)
    }

    /// Number of registered tools.
    #[must_use]
    pub fn tool_count(&self) -> usize {
        self.tools.tool_count()
    }

    /// Register a static MCP resource reader.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a resource with
    /// the same URI is already registered.
    pub fn add_resource<Read>(
        &mut self,
        definition: ResourceDefinition,
        read: Read,
    ) -> Result<(), McpToolError>
    where
        Read: Fn() -> ReadResourceResult + Send + Sync + 'static,
    {
        self.add_resource_async(definition, move || {
            let result = read();
            std::future::ready(Ok(result))
        })
    }

    /// Register an async MCP resource reader.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a resource with
    /// the same URI is already registered.
    pub fn add_resource_async<Read, Fut>(
        &mut self,
        definition: ResourceDefinition,
        read: Read,
    ) -> Result<(), McpToolError>
    where
        Read: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<ReadResourceResult, ErrorData>> + Send + 'static,
    {
        let uri = definition.uri.clone();
        validate_resource_definition(&definition)?;
        if self.resources.contains_key(&uri) {
            return Err(McpToolError::duplicate_resource(uri));
        }

        self.resources.insert(
            uri,
            Arc::new(RegisteredResource {
                definition,
                read: Arc::new(move || Box::pin(read())),
            }),
        );
        Ok(())
    }

    /// Register an MCP resource template advertised by `resources/templates/list`.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid.
    pub fn add_resource_template(
        &mut self,
        definition: ResourceTemplateDefinition,
    ) -> Result<(), McpToolError> {
        validate_resource_template(&definition)?;
        self.resource_templates.push(definition);
        Ok(())
    }

    /// Return registered MCP resource definitions.
    pub fn list_resources(&self) -> Vec<ResourceDefinition> {
        self.resources
            .values()
            .map(|resource| resource.definition())
            .collect()
    }

    /// Return registered MCP resource template definitions.
    pub fn list_resource_templates(&self) -> Vec<ResourceTemplateDefinition> {
        self.resource_templates.clone()
    }

    /// Whether a resource URI is already registered.
    pub fn contains_resource(&self, uri: &str) -> bool {
        self.resources.contains_key(uri)
    }

    /// Number of registered concrete resources.
    pub fn resource_count(&self) -> usize {
        self.resources.len()
    }

    /// Register a static MCP prompt.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a prompt with
    /// the same name is already registered.
    pub fn add_prompt<Get>(
        &mut self,
        definition: PromptDefinition,
        get: Get,
    ) -> Result<(), McpToolError>
    where
        Get: Fn(Option<JsonObject>) -> GetPromptResult + Send + Sync + 'static,
    {
        self.add_prompt_async(definition, move |arguments| {
            let result = get(arguments);
            std::future::ready(Ok(result))
        })
    }

    /// Register an async MCP prompt.
    ///
    /// # Errors
    ///
    /// Returns [`McpToolError`] when `definition` is invalid or a prompt with
    /// the same name is already registered.
    pub fn add_prompt_async<Get, Fut>(
        &mut self,
        definition: PromptDefinition,
        get: Get,
    ) -> Result<(), McpToolError>
    where
        Get: Fn(Option<JsonObject>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<GetPromptResult, ErrorData>> + Send + 'static,
    {
        let name = definition.name.clone();
        validate_prompt_definition(&definition)?;
        if self.prompts.contains_key(&name) {
            return Err(McpToolError::duplicate_prompt(name));
        }

        self.prompts.insert(
            name,
            Arc::new(RegisteredPrompt {
                definition,
                get: Arc::new(move |arguments| Box::pin(get(arguments))),
            }),
        );
        Ok(())
    }

    /// Return registered MCP prompt definitions.
    pub fn list_prompts(&self) -> Vec<PromptDefinition> {
        self.prompts
            .values()
            .map(|prompt| prompt.definition())
            .collect()
    }

    /// Whether a prompt name is already registered.
    pub fn contains_prompt(&self, name: &str) -> bool {
        self.prompts.contains_key(name)
    }

    /// Number of registered prompts.
    pub fn prompt_count(&self) -> usize {
        self.prompts.len()
    }

    /// Calls a registered tool and converts validation or handler failures into
    /// a protocol-level tool result.
    #[must_use]
    pub fn call_tool(&self, name: &str, arguments: Option<Value>) -> ToolCallResult {
        self.tools.call_tool(name, arguments)
    }

    /// Asynchronously calls a registered tool and converts validation or
    /// handler failures into a protocol-level tool result.
    pub async fn call_tool_async(&self, name: &str, arguments: Option<Value>) -> ToolCallResult {
        self.tools.call_tool_async(name, arguments).await
    }

    /// Serve this server over stdin/stdout using the MCP stdio transport.
    ///
    /// # Errors
    ///
    /// Returns an error when stdio serving fails or the service task fails.
    pub async fn serve_stdio(self) -> ServeStdioResult {
        let service = self.serve(stdio()).await?;
        service.waiting().await?;
        Ok(())
    }

    /// Serve this server over stdin/stdout on a new Tokio runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when the Tokio runtime cannot be created, stdio serving
    /// fails, or the service task fails.
    pub fn serve_stdio_blocking(self) -> ServeStdioResult {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()?;
        runtime.block_on(self.serve_stdio())
    }

    fn result_meta(&self) -> MetaObject {
        let mut meta = MetaObject::default();
        meta.0.insert(
            "io.modelcontextprotocol/serverInfo".to_string(),
            json!({
                "name": self.server_name,
                "version": self.server_version,
            }),
        );
        meta
    }

    fn prepare_cacheable_result(
        &self,
        protocol_version: Option<&ProtocolVersion>,
        ttl_ms: &mut Option<u64>,
        cache_scope: &mut Option<CacheScope>,
        meta: &mut Option<MetaObject>,
    ) {
        if protocol_version.is_some_and(|version| version >= &ProtocolVersion::V_2026_07_28) {
            *ttl_ms = Some(0);
            *cache_scope = Some(CacheScope::Private);
        }
        *meta = Some(self.result_meta());
    }
}

/// Builder for composing generated MCP server registrars.
#[derive(Clone)]
pub struct McpServerBuilder {
    server: Result<McpServer, McpToolError>,
}

impl McpServerBuilder {
    /// Create a builder with advertised server metadata.
    pub fn new(
        server_name: impl Into<Cow<'static, str>>,
        server_version: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            server: Ok(McpServer::new(server_name, server_version)),
        }
    }

    /// Runs a registrar against the server being built.
    pub fn register<Register>(mut self, register: Register) -> Self
    where
        Register: FnOnce(&mut McpServer) -> Result<(), McpToolError>,
    {
        if let Ok(server) = self.server.as_mut()
            && let Err(error) = register(server)
        {
            self.server = Err(error);
        }
        self
    }

    /// Add a synchronous MCP tool to the server being built.
    pub fn tool<Call>(self, definition: ToolDefinition, call: Call) -> Self
    where
        Call: Fn(McpToolCall) -> ToolCallResult + Send + Sync + 'static,
    {
        self.register(move |server| server.add_tool(definition, call))
    }

    /// Add a synchronous typed MCP tool to the server being built.
    pub fn typed_tool<Input, Call>(self, definition: McpTypedTool<Input>, call: Call) -> Self
    where
        Input: McpToolInput,
        Call: Fn(Input) -> ToolCallResult + Send + Sync + 'static,
    {
        self.register(move |server| server.add_typed_tool(definition, call))
    }

    /// Add an async MCP tool to the server being built.
    pub fn tool_async<Call, Fut>(self, definition: ToolDefinition, call: Call) -> Self
    where
        Call: Fn(McpToolCall) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        self.register(move |server| server.add_tool_async(definition, call))
    }

    /// Add an async typed MCP tool to the server being built.
    pub fn typed_tool_async<Input, Call, Fut>(
        self,
        definition: McpTypedTool<Input>,
        call: Call,
    ) -> Self
    where
        Input: McpToolInput,
        Call: Fn(Input) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolCallResult> + Send + 'static,
    {
        self.register(move |server| server.add_typed_tool_async(definition, call))
    }

    /// Add a static MCP resource to the server being built.
    pub fn resource<Read>(self, definition: ResourceDefinition, read: Read) -> Self
    where
        Read: Fn() -> ReadResourceResult + Send + Sync + 'static,
    {
        self.register(move |server| server.add_resource(definition, read))
    }

    /// Add an async MCP resource to the server being built.
    pub fn resource_async<Read, Fut>(self, definition: ResourceDefinition, read: Read) -> Self
    where
        Read: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<ReadResourceResult, ErrorData>> + Send + 'static,
    {
        self.register(move |server| server.add_resource_async(definition, read))
    }

    /// Add an MCP resource template to the server being built.
    pub fn resource_template(self, definition: ResourceTemplateDefinition) -> Self {
        self.register(move |server| server.add_resource_template(definition))
    }

    /// Add a static MCP prompt to the server being built.
    pub fn prompt<Get>(self, definition: PromptDefinition, get: Get) -> Self
    where
        Get: Fn(Option<JsonObject>) -> GetPromptResult + Send + Sync + 'static,
    {
        self.register(move |server| server.add_prompt(definition, get))
    }

    /// Add an async MCP prompt to the server being built.
    pub fn prompt_async<Get, Fut>(self, definition: PromptDefinition, get: Get) -> Self
    where
        Get: Fn(Option<JsonObject>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<GetPromptResult, ErrorData>> + Send + 'static,
    {
        self.register(move |server| server.add_prompt_async(definition, get))
    }

    /// Finish the builder and return the composed server.
    ///
    /// # Errors
    ///
    /// Returns the first [`McpToolError`] produced by a builder registrar.
    pub fn build(self) -> Result<McpServer, McpToolError> {
        self.server
    }

    /// Build and serve this server over stdin/stdout using the MCP stdio transport.
    ///
    /// # Errors
    ///
    /// Returns an error when a builder registrar fails, stdio serving fails, or
    /// the service task fails.
    pub async fn serve_stdio(self) -> ServeStdioResult {
        self.build()?.serve_stdio().await
    }

    /// Build and serve this server over stdin/stdout on a new Tokio runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when a builder registrar fails, the Tokio runtime cannot
    /// be created, stdio serving fails, or the service task fails.
    pub fn serve_stdio_blocking(self) -> ServeStdioResult {
        self.build()?.serve_stdio_blocking()
    }
}

impl ServerHandler for McpServer {
    fn get_info(&self) -> ServerInfo {
        let mut capabilities = ServerCapabilities::builder().enable_tools().build();
        capabilities.resources = (!self.resources.is_empty()
            || !self.resource_templates.is_empty())
        .then(Default::default);
        capabilities.prompts = (!self.prompts.is_empty()).then(Default::default);
        ServerInfo::new(capabilities)
            .with_protocol_version(ProtocolVersion::V_2026_07_28)
            .with_server_info(Implementation::new(
                self.server_name.clone(),
                self.server_version.clone(),
            ))
    }

    fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListToolsResult, ErrorData>> + MaybeSendFuture + '_ {
        let mut result = ListToolsResult::with_all_items(self.list_tools());
        self.prepare_cacheable_result(
            context.protocol_version().as_ref(),
            &mut result.ttl_ms,
            &mut result.cache_scope,
            &mut result.meta,
        );
        std::future::ready(Ok(result))
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.tools.definition(name)
    }

    fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<CallToolResponse, ErrorData>> + MaybeSendFuture + '_ {
        let name = request.name.to_string();
        let call = McpToolCall::new(request.arguments.unwrap_or_default());
        let call = match self.tools.resolve_tool(&name, call) {
            Ok((definition, call)) => {
                let output_schema = definition.output_schema;
                let name = name.clone();
                Box::pin(async move {
                    validate_tool_call_result(&name, output_schema.as_deref(), call.await)
                }) as ToolFuture
            },
            Err(error) => {
                let result = tool_error_result_for(error);
                Box::pin(std::future::ready(result))
            },
        };
        let result_meta = self.result_meta();
        async move {
            let mut result = call.await;
            result.meta = Some(result_meta);
            Ok(result.into())
        }
    }

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListResourcesResult, ErrorData>> + MaybeSendFuture + '_ {
        let mut result = ListResourcesResult::with_all_items(self.list_resources());
        self.prepare_cacheable_result(
            context.protocol_version().as_ref(),
            &mut result.ttl_ms,
            &mut result.cache_scope,
            &mut result.meta,
        );
        std::future::ready(Ok(result))
    }

    fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListResourceTemplatesResult, ErrorData>> + MaybeSendFuture + '_
    {
        let mut result =
            ListResourceTemplatesResult::with_all_items(self.list_resource_templates());
        self.prepare_cacheable_result(
            context.protocol_version().as_ref(),
            &mut result.ttl_ms,
            &mut result.cache_scope,
            &mut result.meta,
        );
        std::future::ready(Ok(result))
    }

    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ReadResourceResponse, ErrorData>> + MaybeSendFuture + '_ {
        let uri = request.uri;
        let read = self.resources.get(&uri).map(|resource| resource.read());
        let protocol_version = context.protocol_version();
        let result_meta = self.result_meta();
        async move {
            match read {
                Some(read) => {
                    let mut result = read.await?;
                    if protocol_version
                        .as_ref()
                        .is_some_and(|version| version >= &ProtocolVersion::V_2026_07_28)
                    {
                        result.ttl_ms = Some(0);
                        result.cache_scope = Some(CacheScope::Private);
                    }
                    result.meta = Some(result_meta);
                    Ok(result.into())
                },
                None => Err(ErrorData::resource_not_found(
                    format!("resource `{uri}` not found"),
                    Some(McpToolError::unknown_resource(uri).to_structured_value()),
                )),
            }
        }
    }

    fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListPromptsResult, ErrorData>> + MaybeSendFuture + '_ {
        let mut result = ListPromptsResult::with_all_items(self.list_prompts());
        self.prepare_cacheable_result(
            context.protocol_version().as_ref(),
            &mut result.ttl_ms,
            &mut result.cache_scope,
            &mut result.meta,
        );
        std::future::ready(Ok(result))
    }

    fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<GetPromptResponse, ErrorData>> + MaybeSendFuture + '_ {
        let name = request.name;
        let get = self
            .prompts
            .get(&name)
            .map(|prompt| prompt.get(request.arguments));
        let result_meta = self.result_meta();
        async move {
            match get {
                Some(get) => {
                    let mut result = get.await?;
                    result.meta = Some(result_meta);
                    Ok(result.into())
                },
                None => Err(ErrorData::invalid_params(
                    format!("prompt `{name}` not found"),
                    Some(McpToolError::unknown_prompt(name).to_structured_value()),
                )),
            }
        }
    }
}

trait ToolExecutor: Send + Sync {
    fn definition(&self) -> ToolDefinition;
    fn call(&self, call: McpToolCall) -> ToolFuture;
}

struct RegisteredTool {
    definition: ToolDefinition,
    call: Arc<dyn Fn(McpToolCall) -> ToolFuture + Send + Sync>,
}

impl ToolExecutor for RegisteredTool {
    fn definition(&self) -> ToolDefinition {
        self.definition.clone()
    }

    fn call(&self, call: McpToolCall) -> ToolFuture {
        (self.call)(call)
    }
}

trait ResourceReader: Send + Sync {
    fn definition(&self) -> ResourceDefinition;
    fn read(&self) -> ResourceFuture;
}

struct RegisteredResource {
    definition: ResourceDefinition,
    read: Arc<dyn Fn() -> ResourceFuture + Send + Sync>,
}

impl ResourceReader for RegisteredResource {
    fn definition(&self) -> ResourceDefinition {
        self.definition.clone()
    }

    fn read(&self) -> ResourceFuture {
        (self.read)()
    }
}

trait PromptExecutor: Send + Sync {
    fn definition(&self) -> PromptDefinition;
    fn get(&self, arguments: Option<JsonObject>) -> PromptFuture;
}

struct RegisteredPrompt {
    definition: PromptDefinition,
    get: Arc<dyn Fn(Option<JsonObject>) -> PromptFuture + Send + Sync>,
}

impl PromptExecutor for RegisteredPrompt {
    fn definition(&self) -> PromptDefinition {
        self.definition.clone()
    }

    fn get(&self, arguments: Option<JsonObject>) -> PromptFuture {
        (self.get)(arguments)
    }
}

fn validate_tool_call_result(
    tool_name: &str,
    output_schema: Option<&JsonObject>,
    result: ToolCallResult,
) -> ToolCallResult {
    let Some(output_schema) = output_schema else {
        return result;
    };
    if result.is_error == Some(true) {
        return result;
    }

    let Some(structured_content) = result.structured_content.as_ref() else {
        return tool_error_result_for(McpToolError::invalid_tool_output(
            tool_name,
            "tool declares output_schema but returned no structured_content",
        ));
    };

    let output_schema = Value::Object(output_schema.clone());
    if let Err(error) = validate_value_against_closed_schema(
        "structured_content",
        &output_schema,
        structured_content,
    ) {
        return tool_error_result_for(McpToolError::invalid_tool_output(
            tool_name,
            error.to_string(),
        ));
    }

    result
}

fn block_on_tool_future(future: ToolFuture) -> ToolCallResult {
    let join = std::thread::spawn(move || {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>(runtime.block_on(future))
    })
    .join();

    match join {
        Ok(Ok(result)) => result,
        Ok(Err(error)) => tool_error_result_for(McpToolError::handler(format!(
            "failed to run async tool handler: {error}"
        ))),
        Err(_) => {
            tool_error_result_for(McpToolError::handler("async tool handler runtime panicked"))
        },
    }
}