fastmcp-client 0.7.1

MCP client implementation for FastMCP
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
//! Client session state.

use fastmcp_core::{CanonicalHttpUrl, McpError, McpResult};
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::sync::Arc;

use fastmcp_protocol::common_types::Implementation;
use fastmcp_protocol::extensions::{
    ClientExtensionDiscovery, ExtensionDescriptor, ExtensionDescriptorRegistry, ExtensionDirection,
    ExtensionLocalEnablement, ExtensionNegotiationError, ExtensionSettings,
    ExtensionSettingsCompatibilityResolver, ExtensionSettingsResolution, McpAppsActivationReceipt,
    McpAppsClientSettings, McpAppsNegotiationResolver, NegotiatedExtensionSet,
    ServerExtensionDiscovery, official_mcp_apps_extension_id,
    official_mcp_apps_negotiation_resolver, register_official_mcp_apps_extension,
};
use fastmcp_protocol::protocol_policy::{
    HttpEndpointBundle, HttpEndpointBundleError, ProtocolEra, ProtocolPolicy, ProtocolVersion,
    ProtocolVersionError,
};
use fastmcp_protocol::{
    ClientCapabilities, ClientInfo, ServerCapabilities, ServerDiscoverResult, ServerInfo,
    ServerInstructions,
};

#[cfg(feature = "legacy-2024-11-05")]
const DEFAULT_SESSION_PROTOCOL_POLICY: ProtocolPolicy = ProtocolPolicy::Auto;
#[cfg(not(feature = "legacy-2024-11-05"))]
const DEFAULT_SESSION_PROTOCOL_POLICY: ProtocolPolicy = ProtocolPolicy::ModernOnly;

/// Sized bridge for a caller-provided dynamic client extension-settings resolver.
struct BoxedClientExtensionSettingsResolver(Box<dyn ExtensionSettingsCompatibilityResolver + Send>);

impl ExtensionSettingsCompatibilityResolver for BoxedClientExtensionSettingsResolver {
    fn resolve(
        &mut self,
        descriptor: &ExtensionDescriptor,
        client: &ExtensionSettings,
        server: &ExtensionSettings,
    ) -> Result<ExtensionSettings, ExtensionNegotiationError> {
        self.0.resolve(descriptor, client, server)
    }

    fn resolve_with_disposition(
        &mut self,
        descriptor: &ExtensionDescriptor,
        client: &ExtensionSettings,
        server: &ExtensionSettings,
    ) -> Result<ExtensionSettingsResolution, ExtensionNegotiationError> {
        self.0.resolve_with_disposition(descriptor, client, server)
    }
}

/// Builds one fresh settings resolver for each discovery exchange.
///
/// Extension settings resolvers are deliberately mutable: callers may use
/// them to retain per-negotiation validation state. The builder configuration,
/// however, is cloneable and may retry a connection. Keeping one resolver,
/// including a cloneable `Arc<Mutex<_>>`, would let a failed attempt influence
/// a retry or a cloned builder. This factory keeps the registry and discovery
/// settings immutable and invokes the caller's constructor for every
/// negotiation attempt.
trait ClientExtensionSettingsResolverFactory: Send + Sync {
    fn fresh_resolver(&self) -> BoxedClientExtensionSettingsResolver;
}

struct FreshClientExtensionSettingsResolverFactory<F, R> {
    factory: F,
    wraps_mcp_apps: bool,
    marker: PhantomData<fn() -> R>,
}

impl<F, R> ClientExtensionSettingsResolverFactory
    for FreshClientExtensionSettingsResolverFactory<F, R>
where
    F: Fn() -> R + Send + Sync + 'static,
    R: ExtensionSettingsCompatibilityResolver + Send + 'static,
{
    fn fresh_resolver(&self) -> BoxedClientExtensionSettingsResolver {
        let resolver = BoxedClientExtensionSettingsResolver(Box::new((self.factory)()));
        if self.wraps_mcp_apps {
            BoxedClientExtensionSettingsResolver(Box::new(
                McpAppsNegotiationResolver::with_fallback(resolver),
            ))
        } else {
            resolver
        }
    }
}

/// Immutable extension configuration frozen by [`crate::ClientBuilder`].
///
/// The descriptor receipt, local enablement, and client settings stay together
/// so a connection can negotiate once from `server/discover` and admit later
/// raw extension requests against that exact state.
#[derive(Clone)]
pub(crate) struct ClientExtensionRuntime {
    descriptors: ExtensionDescriptorRegistry,
    local_enablement: ExtensionLocalEnablement,
    client_discovery: ClientExtensionDiscovery,
    resolver_factory: Arc<dyn ClientExtensionSettingsResolverFactory>,
}

impl std::fmt::Debug for ClientExtensionRuntime {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ClientExtensionRuntime")
            .field("descriptor_count", &self.descriptors.descriptors().len())
            .field(
                "configured_extension_count",
                &self.client_discovery.extensions.len(),
            )
            .field("frozen", &self.descriptors.receipt().is_some())
            .finish_non_exhaustive()
    }
}

impl ClientExtensionRuntime {
    pub(crate) fn new<F, R>(
        mut descriptors: ExtensionDescriptorRegistry,
        client_discovery: ClientExtensionDiscovery,
        resolver_factory: F,
    ) -> McpResult<Self>
    where
        F: Fn() -> R + Send + Sync + 'static,
        R: ExtensionSettingsCompatibilityResolver + Send + 'static,
    {
        for extension_id in client_discovery.extensions.keys() {
            if descriptors.descriptor(extension_id).is_none() {
                return Err(McpError::invalid_params(format!(
                    "Client extension settings reference an unregistered descriptor: {extension_id}"
                )));
            }
        }
        descriptors.freeze().map_err(|error| {
            McpError::invalid_params(format!(
                "Client extension descriptor registry could not be frozen: {error}"
            ))
        })?;

        let mut local_enablement = ExtensionLocalEnablement::default();
        for extension_id in client_discovery.extensions.keys() {
            local_enablement.enable(extension_id.clone());
        }

        let wraps_mcp_apps = client_discovery
            .extensions
            .contains_key(&official_mcp_apps_extension_id());

        Ok(Self {
            descriptors,
            local_enablement,
            client_discovery,
            resolver_factory: Arc::new(FreshClientExtensionSettingsResolverFactory {
                factory: resolver_factory,
                wraps_mcp_apps,
                marker: PhantomData,
            }),
        })
    }

    pub(crate) fn client_wire_extensions(&self) -> BTreeMap<String, serde_json::Value> {
        self.client_discovery
            .extensions
            .iter()
            .map(|(id, settings)| (id.to_string(), settings.clone().into_value()))
            .collect()
    }

    pub(crate) fn negotiate(
        &self,
        discovery: &ServerDiscoverResult,
    ) -> McpResult<NegotiatedExtensionSet> {
        let capabilities = serde_json::to_value(discovery.capabilities()).map_err(|error| {
            McpError::internal_error(format!(
                "Final server/discover capabilities could not be retained for extension negotiation: {error}"
            ))
        })?;
        let extensions = capabilities
            .get("extensions")
            .and_then(serde_json::Value::as_object);
        let mut server = ServerExtensionDiscovery::default();
        if let Some(extensions) = extensions {
            for (name, settings) in extensions {
                let extension_id = fastmcp_protocol::ExtensionId::parse(name).map_err(|_| {
                    McpError::invalid_params(
                        "Final server/discover contains an invalid extension identifier",
                    )
                })?;
                let settings = ExtensionSettings::new(settings.clone()).map_err(|_| {
                    McpError::invalid_params(
                        "Final server/discover contains invalid extension settings",
                    )
                })?;
                server.extensions.insert(extension_id, settings);
            }
        }

        let mut resolver = self.resolver_factory.fresh_resolver();
        self.descriptors
            .negotiate(
                ProtocolEra::Modern2026,
                &self.local_enablement,
                &self.client_discovery,
                &server,
                &mut resolver,
            )
            .map_err(|error| {
                McpError::invalid_params(format!(
                    "Final client extension negotiation failed: {error}"
                ))
            })
    }

    pub(crate) fn admit_method(
        &self,
        negotiated: &NegotiatedExtensionSet,
        extension_id: &fastmcp_protocol::ExtensionId,
        method: &str,
    ) -> McpResult<()> {
        negotiated
            .admit_method(
                &self.descriptors,
                ProtocolEra::Modern2026,
                extension_id,
                method,
                ExtensionDirection::ClientToServer,
            )
            .map(|_| ())
            .map_err(|error| {
                McpError::invalid_params(format!(
                    "Final extension request is not admitted by the negotiated client capability: {error}"
                ))
            })
    }

    /// Returns whether a configured descriptor owns this raw request method.
    ///
    /// Public raw request surfaces use this to ensure a registered extension
    /// method cannot bypass final-era admission through a generic JSON-RPC
    /// method string.
    pub(crate) fn owns_method(&self, method: &str) -> bool {
        self.descriptors.descriptors().any(|descriptor| {
            self.descriptors
                .method_descriptor(&descriptor.id, method)
                .is_some()
        })
    }

    pub(crate) fn configures_mcp_apps(&self) -> bool {
        self.client_discovery
            .extensions
            .contains_key(&official_mcp_apps_extension_id())
    }

    pub(crate) fn configures_extension(&self, extension_id: &str) -> bool {
        self.client_discovery
            .extensions
            .keys()
            .any(|configured| configured.as_str() == extension_id)
    }

    pub(crate) fn mcp_apps_activation_receipt(
        &self,
        negotiated: &NegotiatedExtensionSet,
    ) -> Option<McpAppsActivationReceipt> {
        negotiated.mcp_apps_activation_receipt(&self.descriptors)
    }
}

/// Immutable transport policy and trusted endpoint configuration for one client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientProtocolPlan {
    policy: ProtocolPolicy,
    http_endpoints: Option<HttpEndpointBundle>,
    modern_post_target: Option<String>,
    legacy_sse_target: Option<String>,
    legacy_message_post_target: Option<String>,
}

impl ClientProtocolPlan {
    #[must_use]
    pub const fn stdio(policy: ProtocolPolicy) -> Self {
        Self {
            policy,
            http_endpoints: None,
            modern_post_target: None,
            legacy_sse_target: None,
            legacy_message_post_target: None,
        }
    }

    /// Creates an immutable protocol selection for one WebSocket connection.
    ///
    /// A WebSocket is one long-lived bidirectional connection. `Auto` uses a
    /// caller-owned fresh-transport factory: it performs final discovery on
    /// the first connection and, only after a correlated `MethodNotFound`, may
    /// establish one fresh connection for exact-2024 initialization. It never
    /// replays initialization on the refused connection. The selected era is
    /// frozen before ordinary requests can be issued.
    #[must_use]
    pub const fn websocket(policy: ProtocolPolicy) -> Self {
        Self::stdio(policy)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn http(
        policy: ProtocolPolicy,
        modern_post: Option<CanonicalHttpUrl>,
        legacy_sse: Option<CanonicalHttpUrl>,
        legacy_message_post: Option<CanonicalHttpUrl>,
        credential_partition: String,
        security_partition: String,
        transport_profile: String,
        policy_generation: u64,
        configuration_generation: u64,
        legacy_receipt_generation: u64,
    ) -> Result<Self, HttpEndpointBundleError> {
        let modern_post_target = modern_post
            .as_ref()
            .map(|target| target.as_str().to_owned());
        let legacy_sse_target = legacy_sse.as_ref().map(|target| target.as_str().to_owned());
        let legacy_message_post_target = legacy_message_post
            .as_ref()
            .map(|target| target.as_str().to_owned());
        let http_endpoints = HttpEndpointBundle::new(
            policy,
            modern_post,
            legacy_sse,
            legacy_message_post,
            credential_partition,
            security_partition,
            transport_profile,
            policy_generation,
            configuration_generation,
            legacy_receipt_generation,
        )?;
        Ok(Self {
            policy,
            http_endpoints: Some(http_endpoints),
            modern_post_target,
            legacy_sse_target,
            legacy_message_post_target,
        })
    }

    #[must_use]
    pub const fn policy(&self) -> ProtocolPolicy {
        self.policy
    }

    #[must_use]
    pub const fn http_endpoints(&self) -> Option<&HttpEndpointBundle> {
        self.http_endpoints.as_ref()
    }

    /// Returns the exact configured canonical modern MCP POST target.
    ///
    /// The protocol bundle intentionally keeps route strings opaque for
    /// negotiation-cache identity. The native HTTP runtime still needs the
    /// configured target to issue its one disposable modern probe and the
    /// subsequent modern requests, so this accessor exposes only that route.
    #[must_use]
    pub fn modern_post_target(&self) -> Option<&str> {
        self.modern_post_target.as_deref()
    }

    /// Returns the exact configured canonical legacy SSE GET target.
    ///
    /// This value is copied from the validated endpoint input before the
    /// opaque bundle is built. The HTTP runtime uses it only to open the
    /// legacy event stream; it never derives a route from an observed event.
    #[must_use]
    pub fn legacy_sse_target(&self) -> Option<&str> {
        self.legacy_sse_target.as_deref()
    }

    /// Returns the exact configured canonical legacy message POST target.
    ///
    /// A legacy SSE endpoint advertisement must exactly match this immutable
    /// target before the runtime permits a JSON-RPC POST.
    #[must_use]
    pub fn legacy_message_post_target(&self) -> Option<&str> {
        self.legacy_message_post_target.as_deref()
    }
}

/// Rejection for a protocol plan that contradicts an already negotiated era.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClientProtocolPlanError {
    /// The plan's immutable policy forbids the era selected by the handshake.
    IncompatibleSelectedEra {
        /// The era selected by the completed handshake.
        selected_era: ProtocolEra,
        /// The policy that does not permit the selected era.
        policy: ProtocolPolicy,
    },
}

impl std::fmt::Display for ClientProtocolPlanError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IncompatibleSelectedEra {
                selected_era,
                policy,
            } => write!(
                formatter,
                "protocol policy {policy:?} does not permit negotiated era {selected_era:?}"
            ),
        }
    }
}

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

/// Client-side session state.
#[derive(Debug, Clone)]
pub struct ClientSession {
    /// Client info sent during initialization.
    client_info: ClientInfo,
    /// Modern Implementation extras retained from the builder, if any.
    client_implementation: Option<Implementation>,
    /// Client capabilities sent during initialization.
    client_capabilities: ClientCapabilities,
    /// Server info received during initialization.
    server_info: ServerInfo,
    /// Server capabilities received during initialization.
    server_capabilities: ServerCapabilities,
    /// Exact final discovery state when the modern handshake succeeded.
    ///
    /// Legacy initialization retains instructions separately via
    /// [`Self::legacy_instructions`]. Discovery capabilities, result
    /// metadata, and cache hints remain modern-only.
    server_discovery: Option<ServerDiscoverResult>,
    /// Exact-2024 `initialize` instructions retained from the handshake.
    ///
    /// Modern sessions leave this empty and prefer the lossless discovery
    /// string. `None` means the peer did not advertise instructions.
    legacy_instructions: Option<String>,
    /// Local MCP Apps settings selected before connection.
    mcp_apps_settings: Option<McpAppsClientSettings>,
    /// Opaque bilateral Apps receipt retained from the current modern discovery
    /// exchange. Legacy and inactive sessions deliberately retain no receipt.
    mcp_apps_activation_receipt: Option<McpAppsActivationReceipt>,
    /// Immutable generic extension configuration installed by the builder.
    client_extension_runtime: Option<Arc<ClientExtensionRuntime>>,
    /// Frozen bilateral extension state retained from the successful final
    /// discovery exchange. Legacy sessions deliberately retain no set.
    negotiated_extensions: Option<NegotiatedExtensionSet>,
    /// Negotiated protocol version.
    protocol_version: String,
    /// Immutable era selected from the successful handshake.
    selected_era: Option<ProtocolEra>,
    /// Immutable policy and configured endpoint bundle for this client.
    protocol_plan: ClientProtocolPlan,
}

impl ClientSession {
    /// Creates a session only when the negotiated protocol version is supported.
    ///
    /// Callers completing a handshake must use this constructor so an
    /// unsupported wire spelling cannot create a session or select an era.
    pub fn try_new(
        client_info: ClientInfo,
        client_capabilities: ClientCapabilities,
        server_info: ServerInfo,
        server_capabilities: ServerCapabilities,
        protocol_version: String,
    ) -> Result<Self, ProtocolVersionError> {
        let selected_era = ProtocolVersion::parse(&protocol_version)?.era();
        Ok(Self::from_parts(
            client_info,
            client_capabilities,
            server_info,
            server_capabilities,
            protocol_version,
            Some(selected_era),
        ))
    }

    /// Creates the unselected placeholder state used before initialization.
    #[must_use]
    pub(crate) fn new_placeholder(
        client_info: ClientInfo,
        client_capabilities: ClientCapabilities,
        server_info: ServerInfo,
        server_capabilities: ServerCapabilities,
    ) -> Self {
        Self::from_parts(
            client_info,
            client_capabilities,
            server_info,
            server_capabilities,
            String::new(),
            None,
        )
    }

    fn from_parts(
        client_info: ClientInfo,
        client_capabilities: ClientCapabilities,
        server_info: ServerInfo,
        server_capabilities: ServerCapabilities,
        protocol_version: String,
        selected_era: Option<ProtocolEra>,
    ) -> Self {
        Self {
            client_info,
            client_implementation: None,
            client_capabilities,
            server_info,
            server_capabilities,
            server_discovery: None,
            legacy_instructions: None,
            mcp_apps_settings: None,
            mcp_apps_activation_receipt: None,
            client_extension_runtime: None,
            negotiated_extensions: None,
            selected_era,
            protocol_version,
            // A peer-selected era must never rewrite the pre-connect policy.
            protocol_plan: ClientProtocolPlan::stdio(DEFAULT_SESSION_PROTOCOL_POLICY),
        }
    }

    /// Applies a plan only when it admits the already negotiated era.
    pub fn try_with_protocol_plan(
        mut self,
        protocol_plan: ClientProtocolPlan,
    ) -> Result<Self, ClientProtocolPlanError> {
        self.validate_protocol_plan(&protocol_plan)?;
        self.protocol_plan = protocol_plan;
        Ok(self)
    }

    /// Applies a plan that admits the already negotiated era.
    ///
    /// Prefer [`Self::try_with_protocol_plan`] when the plan comes from an
    /// external caller or configuration source.
    ///
    /// # Panics
    ///
    /// Panics when `protocol_plan` forbids the era selected by this session.
    #[must_use]
    pub fn with_protocol_plan(self, protocol_plan: ClientProtocolPlan) -> Self {
        self.try_with_protocol_plan(protocol_plan)
            .expect("protocol plan must admit the negotiated era")
    }

    pub(crate) fn with_server_discovery(mut self, server_discovery: ServerDiscoverResult) -> Self {
        self.server_discovery = Some(server_discovery);
        self
    }

    pub(crate) fn with_legacy_instructions(mut self, instructions: Option<String>) -> Self {
        self.legacy_instructions = instructions;
        self
    }

    pub(crate) fn with_mcp_apps_settings(
        mut self,
        settings: Option<McpAppsClientSettings>,
    ) -> Self {
        self.mcp_apps_settings = settings;
        self
    }

    pub(crate) fn with_client_extension_runtime(
        mut self,
        runtime: Option<Arc<ClientExtensionRuntime>>,
    ) -> Self {
        self.client_extension_runtime = runtime;
        self
    }

    pub(crate) fn client_extension_runtime(&self) -> Option<&Arc<ClientExtensionRuntime>> {
        self.client_extension_runtime.as_ref()
    }

    pub(crate) fn client_extension_wire_settings(
        &self,
    ) -> Option<BTreeMap<String, serde_json::Value>> {
        self.client_extension_runtime
            .as_ref()
            .map(|runtime| runtime.client_wire_extensions())
    }

    pub(crate) fn negotiate_client_extensions_after_discovery(&mut self) -> McpResult<()> {
        if self.selected_era != Some(ProtocolEra::Modern2026) {
            self.negotiated_extensions = None;
            return Ok(());
        }
        let Some(runtime) = self.client_extension_runtime.as_ref() else {
            return Ok(());
        };
        let discovery = self.server_discovery.as_ref().ok_or_else(|| {
            McpError::internal_error(
                "Final client extension negotiation requires retained server/discover state",
            )
        })?;
        self.negotiated_extensions = Some(runtime.negotiate(discovery)?);
        Ok(())
    }

    pub(crate) fn admit_final_extension_method(
        &self,
        extension_id: &fastmcp_protocol::ExtensionId,
        method: &str,
    ) -> McpResult<()> {
        if self.selected_era != Some(ProtocolEra::Modern2026) {
            return Err(McpError::invalid_params(
                "Final client extensions are unavailable in exact MCP 2024-11-05",
            ));
        }
        let runtime = self.client_extension_runtime.as_ref().ok_or_else(|| {
            McpError::invalid_params(
                "No builder-owned final client extension registry is configured",
            )
        })?;
        let negotiated = self.negotiated_extensions.as_ref().ok_or_else(|| {
            McpError::invalid_params(
                "Final client extension settings were not negotiated by server/discover",
            )
        })?;
        runtime.admit_method(negotiated, extension_id, method)
    }

    pub(crate) fn set_mcp_apps_activation_receipt(
        &mut self,
        receipt: Option<McpAppsActivationReceipt>,
    ) {
        self.mcp_apps_activation_receipt = receipt;
    }

    pub(crate) fn mcp_apps_settings(&self) -> Option<&McpAppsClientSettings> {
        self.mcp_apps_settings.as_ref()
    }

    /// Returns the Apps receipt derived from the builder-owned generic
    /// registry when that registry owns the official Apps descriptor.
    ///
    /// This is deliberately distinct from the compatibility-only dedicated
    /// Apps settings path: once Apps travels through `extension_registry`,
    /// the frozen registry and its negotiated set are the only authority.
    pub(crate) fn generic_mcp_apps_activation_receipt(&self) -> Option<McpAppsActivationReceipt> {
        let runtime = self.client_extension_runtime.as_ref()?;
        runtime.configures_mcp_apps().then_some(())?;
        let negotiated = self.negotiated_extensions.as_ref()?;
        runtime.mcp_apps_activation_receipt(negotiated)
    }

    pub(crate) fn generic_mcp_apps_configured(&self) -> bool {
        self.client_extension_runtime
            .as_ref()
            .is_some_and(|runtime| runtime.configures_mcp_apps())
    }

    /// Returns whether MCP Apps was bilaterally activated during final discovery.
    #[cfg(feature = "apps")]
    #[must_use]
    pub const fn mcp_apps_active(&self) -> bool {
        self.mcp_apps_activation_receipt.is_some()
    }

    /// Returns the immutable generic extension set negotiated from the final
    /// `server/discover` exchange, if this session selected MCP 2026-07-28
    /// and the builder installed a client extension registry.
    #[must_use]
    pub fn negotiated_extensions(&self) -> Option<&NegotiatedExtensionSet> {
        self.negotiated_extensions.as_ref()
    }

    /// Returns the immutable current Apps activation receipt, if modern
    /// discovery negotiated the official extension bilaterally.
    #[must_use]
    pub(crate) fn mcp_apps_activation_receipt(&self) -> Option<&McpAppsActivationReceipt> {
        self.mcp_apps_activation_receipt.as_ref()
    }

    pub(crate) fn set_protocol_plan(&mut self, protocol_plan: ClientProtocolPlan) {
        self.validate_protocol_plan(&protocol_plan)
            .expect("protocol plan must admit the negotiated era");
        self.protocol_plan = protocol_plan;
    }

    fn validate_protocol_plan(
        &self,
        protocol_plan: &ClientProtocolPlan,
    ) -> Result<(), ClientProtocolPlanError> {
        let Some(selected_era) = self.selected_era else {
            return Ok(());
        };
        if protocol_plan.policy().permits(selected_era.version()) {
            Ok(())
        } else {
            Err(ClientProtocolPlanError::IncompatibleSelectedEra {
                selected_era,
                policy: protocol_plan.policy(),
            })
        }
    }

    /// Returns the client info.
    #[must_use]
    pub fn client_info(&self) -> &ClientInfo {
        &self.client_info
    }

    /// Returns the modern Implementation identity for this session.
    ///
    /// Builder extras (title/description/website/icons) are retained when
    /// present. Otherwise this projects name and version only.
    #[must_use]
    pub fn modern_client_implementation(&self) -> Implementation {
        self.client_implementation
            .clone()
            .unwrap_or_else(|| self.client_info.to_implementation())
    }

    /// Retains a modern Implementation identity without changing exact-2024
    /// `clientInfo` name/version.
    #[must_use]
    pub fn with_client_implementation(mut self, implementation: Implementation) -> Self {
        self.client_implementation = Some(implementation);
        self
    }

    /// Returns the client capabilities.
    #[must_use]
    pub fn client_capabilities(&self) -> &ClientCapabilities {
        &self.client_capabilities
    }

    /// Returns the server info.
    #[must_use]
    pub fn server_info(&self) -> &ServerInfo {
        &self.server_info
    }

    /// Returns the server capabilities.
    #[must_use]
    pub fn server_capabilities(&self) -> &ServerCapabilities {
        &self.server_capabilities
    }

    /// Returns the lossless final `server/discover` result when modern
    /// negotiation succeeded.
    ///
    /// A `None` value denotes the exact 2024-11-05 initialization path (or a
    /// session that has not yet negotiated). Callers using final MCP must use
    /// this result instead of the legacy [`Self::server_capabilities`] view.
    #[must_use]
    pub fn server_discovery(&self) -> Option<&ServerDiscoverResult> {
        self.server_discovery.as_ref()
    }

    /// Returns the exact-2024 initialize instructions when the handshake
    /// retained them. Modern sessions leave this empty.
    #[must_use]
    pub fn legacy_instructions(&self) -> Option<&str> {
        self.legacy_instructions.as_deref()
    }

    /// Returns server instructions retained from the successful handshake.
    ///
    /// Modern sessions prefer the final discovery string. Exact 2024-11-05
    /// sessions return the initialize result field. A missing value means the
    /// peer did not advertise instructions.
    #[must_use]
    pub fn instructions(&self) -> Option<&str> {
        if let Some(discovery) = self.server_discovery.as_ref() {
            return discovery.instructions().map(ServerInstructions::as_str);
        }
        self.legacy_instructions.as_deref()
    }

    /// Returns the negotiated protocol version.
    #[must_use]
    pub fn protocol_version(&self) -> &str {
        &self.protocol_version
    }

    /// Returns the immutable era selected by the successful handshake.
    ///
    /// Placeholder sessions used before initialization have no selected era.
    #[must_use]
    pub const fn selected_era(&self) -> Option<ProtocolEra> {
        self.selected_era
    }

    #[must_use]
    pub const fn protocol_plan(&self) -> &ClientProtocolPlan {
        &self.protocol_plan
    }
}

/// Resolves the official Apps settings from a final discovery reply.
///
/// Absent or incompatible peer settings deliberately leave Apps inactive. The
/// public protocol decoder has already bounded the discovery capability shape;
/// this helper only interprets the registered official descriptor.
pub(crate) fn mcp_apps_activation_receipt(
    client_settings: Option<&McpAppsClientSettings>,
    discovery: &ServerDiscoverResult,
) -> Option<McpAppsActivationReceipt> {
    let client_settings = client_settings?;
    let capabilities = serde_json::to_value(discovery.capabilities()).ok()?;
    let server_settings = capabilities
        .get("extensions")
        .and_then(serde_json::Value::as_object)
        .and_then(|extensions| extensions.get(official_mcp_apps_extension_id().as_str()))
        .cloned()?;
    let server_settings = ExtensionSettings::new(server_settings).ok()?;
    let mut registry = ExtensionDescriptorRegistry::new();
    let apps_extension = register_official_mcp_apps_extension(&mut registry).ok()?;
    registry.freeze().ok()?;

    let mut local = ExtensionLocalEnablement::default();
    local.enable(apps_extension.clone());
    let client = ClientExtensionDiscovery {
        extensions: BTreeMap::from([(
            apps_extension.clone(),
            client_settings.to_extension_settings(),
        )]),
    };
    let server = ServerExtensionDiscovery {
        extensions: BTreeMap::from([(apps_extension, server_settings)]),
    };
    let mut resolver = official_mcp_apps_negotiation_resolver();
    registry
        .negotiate(
            ProtocolEra::Modern2026,
            &local,
            &client,
            &server,
            &mut resolver,
        )
        .ok()?
        .mcp_apps_activation_receipt(&registry)
}

/// Compatibility predicate for callers that only need to advertise Apps over
/// an already-negotiated HTTP connection. Session-bearing clients retain the
/// opaque receipt through [`mcp_apps_activation_receipt`] instead.
pub(crate) fn resolve_mcp_apps_activation(
    client_settings: Option<&McpAppsClientSettings>,
    discovery: &ServerDiscoverResult,
) -> bool {
    mcp_apps_activation_receipt(client_settings, discovery).is_some()
}

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

    #[cfg(feature = "apps")]
    fn apps_discovery(server_settings: serde_json::Value) -> ServerDiscoverResult {
        serde_json::from_value(serde_json::json!({
            "resultType": "complete",
            "supportedVersions": ["2026-07-28"],
            "capabilities": {
                "extensions": {
                    "io.modelcontextprotocol/ui": server_settings
                }
            },
            "_meta": {
                "io.modelcontextprotocol/serverInfo": {"name": "apps-server", "version": "1.0"}
            },
            "ttlMs": 0,
            "cacheScope": "private"
        }))
        .expect("valid final Apps discovery reply")
    }

    #[cfg(feature = "apps")]
    #[test]
    fn mcp_apps_activation_requires_html_mime_with_the_same_server_marker() {
        let discovery = apps_discovery(serde_json::json!({}));
        let active = McpAppsClientSettings::new(vec!["text/html;profile=mcp-app".to_owned()])
            .expect("valid Apps MIME settings");
        let inactive = McpAppsClientSettings::new(vec!["text/html".to_owned()])
            .expect("valid non-Apps MIME settings");

        assert!(resolve_mcp_apps_activation(Some(&active), &discovery));
        assert!(
            !resolve_mcp_apps_activation(Some(&inactive), &discovery),
            "only the advertised Apps HTML MIME differs"
        );
    }

    #[cfg(feature = "apps")]
    #[test]
    fn generic_apps_runtime_derives_the_same_frozen_activation_receipt() {
        let mut registry = ExtensionDescriptorRegistry::new();
        let apps_id = register_official_mcp_apps_extension(&mut registry)
            .expect("official Apps descriptor registers before builder freeze");
        let settings = McpAppsClientSettings::new(vec!["text/html;profile=mcp-app".to_owned()])
            .expect("Apps HTML profile settings are valid");
        let runtime = ClientExtensionRuntime::new(
            registry,
            ClientExtensionDiscovery {
                extensions: std::collections::BTreeMap::from([(
                    apps_id,
                    settings.to_extension_settings(),
                )]),
            },
            official_mcp_apps_negotiation_resolver,
        )
        .expect("generic builder runtime freezes the official Apps descriptor");
        let negotiated = runtime
            .negotiate(&apps_discovery(serde_json::json!({})))
            .expect("generic Apps settings negotiate against the empty server marker");

        assert!(runtime.configures_mcp_apps());
        assert!(
            runtime.mcp_apps_activation_receipt(&negotiated).is_some(),
            "the generic frozen registry, rather than a second Apps constructor, owns activation"
        );
    }

    use fastmcp_protocol::protocol_policy::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
    use fastmcp_protocol::{PromptsCapability, ResourcesCapability, ToolsCapability};

    fn test_session_with_protocol_version(protocol_version: &str) -> ClientSession {
        try_test_session_with_protocol_version(protocol_version)
            .expect("test sessions use an exact supported protocol version")
    }

    fn try_test_session_with_protocol_version(
        protocol_version: &str,
    ) -> Result<ClientSession, ProtocolVersionError> {
        ClientSession::try_new(
            ClientInfo {
                name: "test-client".to_string(),
                version: "1.0.0".to_string(),
            },
            ClientCapabilities::default(),
            ServerInfo {
                name: "test-server".to_string(),
                version: "2.0.0".to_string(),
            },
            ServerCapabilities {
                tools: Some(ToolsCapability { list_changed: true }),
                resources: Some(ResourcesCapability {
                    subscribe: true,
                    list_changed: false,
                }),
                prompts: Some(PromptsCapability {
                    list_changed: false,
                }),
                logging: None,
                completions: None,
                tasks: None,
            },
            protocol_version.to_owned(),
        )
    }

    fn test_session() -> ClientSession {
        test_session_with_protocol_version(LEGACY_PROTOCOL_VERSION)
    }

    #[test]
    fn session_client_info() {
        let session = test_session();
        assert_eq!(session.client_info().name, "test-client");
        assert_eq!(session.client_info().version, "1.0.0");
    }

    #[test]
    fn session_client_capabilities() {
        let session = test_session();
        let caps = session.client_capabilities();
        assert!(caps.sampling.is_none());
        assert!(caps.elicitation.is_none());
        assert!(caps.roots.is_none());
    }

    #[test]
    fn session_server_info() {
        let session = test_session();
        assert_eq!(session.server_info().name, "test-server");
        assert_eq!(session.server_info().version, "2.0.0");
    }

    #[test]
    fn session_server_capabilities() {
        let session = test_session();
        let caps = session.server_capabilities();
        assert!(caps.tools.is_some());
        assert!(caps.tools.as_ref().unwrap().list_changed);
        assert!(caps.resources.is_some());
        assert!(caps.resources.as_ref().unwrap().subscribe);
        assert!(!caps.resources.as_ref().unwrap().list_changed);
        assert!(caps.prompts.is_some());
        assert!(caps.logging.is_none());
        assert!(caps.tasks.is_none());
    }

    #[test]
    fn session_protocol_version() {
        let session = test_session();
        assert_eq!(session.protocol_version(), LEGACY_PROTOCOL_VERSION);
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn session_default_protocol_plan_remains_auto_after_era_selection() {
        let modern = test_session_with_protocol_version(MODERN_PROTOCOL_VERSION);
        let legacy = test_session();

        assert_eq!(modern.selected_era(), Some(ProtocolEra::Modern2026));
        assert_eq!(legacy.selected_era(), Some(ProtocolEra::Legacy2024));
        assert_eq!(modern.protocol_plan().policy(), ProtocolPolicy::Auto);
        assert_eq!(legacy.protocol_plan().policy(), ProtocolPolicy::Auto);
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn feature_off_session_default_protocol_plan_is_modern_only() {
        let modern = test_session_with_protocol_version(MODERN_PROTOCOL_VERSION);

        assert_eq!(modern.selected_era(), Some(ProtocolEra::Modern2026));
        assert_eq!(modern.protocol_plan().policy(), ProtocolPolicy::ModernOnly);
    }

    #[test]
    fn session_rejects_plan_that_forbids_the_negotiated_era() {
        let error = test_session()
            .try_with_protocol_plan(ClientProtocolPlan::stdio(ProtocolPolicy::ModernOnly))
            .expect_err("a modern-only plan cannot be applied to a legacy session");

        assert_eq!(
            error,
            ClientProtocolPlanError::IncompatibleSelectedEra {
                selected_era: ProtocolEra::Legacy2024,
                policy: ProtocolPolicy::ModernOnly,
            }
        );
    }

    #[test]
    fn session_try_new_preserves_admitted_configured_policy() {
        let session = try_test_session_with_protocol_version(LEGACY_PROTOCOL_VERSION)
            .expect("the supported legacy version constructs a session")
            .try_with_protocol_plan(ClientProtocolPlan::stdio(ProtocolPolicy::LegacyOnly))
            .expect("the configured legacy-only policy admits the legacy session");

        assert_eq!(session.selected_era(), Some(ProtocolEra::Legacy2024));
        assert_eq!(session.protocol_plan().policy(), ProtocolPolicy::LegacyOnly);
    }

    #[test]
    fn session_try_new_rejects_unsupported_protocol_version() {
        let error = try_test_session_with_protocol_version("2025-11-25")
            .expect_err("only the peer version differs from the supported positive case");

        assert_eq!(
            error,
            ProtocolVersionError::UnsupportedVersion {
                received: "2025-11-25".to_string(),
            }
        );
    }

    #[test]
    fn session_with_sampling_capabilities() {
        let session = ClientSession::try_new(
            ClientInfo {
                name: "sampler".to_string(),
                version: "0.1.0".to_string(),
            },
            ClientCapabilities {
                sampling: Some(fastmcp_protocol::SamplingCapability {}),
                elicitation: None,
                roots: None,
            },
            ServerInfo {
                name: "srv".to_string(),
                version: "1.0.0".to_string(),
            },
            ServerCapabilities::default(),
            "2024-11-05".to_string(),
        )
        .expect("exact supported protocol version");
        assert!(session.client_capabilities().sampling.is_some());
    }

    #[test]
    fn session_retains_legacy_initialize_instructions() {
        let session = test_session();
        assert_eq!(session.instructions(), None);
        assert_eq!(session.legacy_instructions(), None);

        let session = session.with_legacy_instructions(Some("use the tools".to_owned()));
        assert_eq!(session.instructions(), Some("use the tools"));
        assert_eq!(session.legacy_instructions(), Some("use the tools"));
    }

    #[test]
    fn session_without_legacy_instructions_stays_bare() {
        let session = test_session().with_legacy_instructions(None);
        assert_eq!(session.instructions(), None);
        assert_eq!(session.legacy_instructions(), None);
    }

    #[test]
    fn session_with_empty_server_capabilities() {
        let session = ClientSession::new_placeholder(
            ClientInfo {
                name: "c".to_string(),
                version: "0.1.0".to_string(),
            },
            ClientCapabilities::default(),
            ServerInfo {
                name: "s".to_string(),
                version: "0.1.0".to_string(),
            },
            ServerCapabilities::default(),
        );
        assert!(session.server_capabilities().tools.is_none());
        assert!(session.server_capabilities().resources.is_none());
        assert!(session.server_capabilities().prompts.is_none());
        assert!(session.server_capabilities().logging.is_none());
        assert!(session.server_capabilities().tasks.is_none());
        assert_eq!(session.protocol_version().len(), 0);
    }
}