blyte 0.88.2

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
//! MCP server configuration (`mcpServers` JSON), `${ENV_VAR}` expansion, and project trust tracking.

use std::collections::BTreeMap;
use std::fmt;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

/// Default transport kind for an MCP server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
#[value(rename_all = "lowercase")]
pub enum TransportKind {
    Stdio,
    #[serde(alias = "streamable-http", alias = "streamable_http")]
    Http,
}

impl TransportKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Stdio => "stdio",
            Self::Http => "http",
        }
    }
}

impl fmt::Display for TransportKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Tool approval policy for an MCP server.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalPolicy {
    #[default]
    #[value(name = "read_only")]
    ReadOnly,
    #[value(name = "auto")]
    Auto,
    #[value(name = "ask")]
    Ask,
}

impl ApprovalPolicy {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::ReadOnly => "read_only",
            Self::Auto => "auto",
            Self::Ask => "ask",
        }
    }
}

impl fmt::Display for ApprovalPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Origin of a configured MCP server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServerSource {
    User,
    Project,
}

impl ServerSource {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Project => "project",
        }
    }
}

impl fmt::Display for ServerSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

fn default_enabled() -> bool {
    true
}

/// Optional pre-registered OAuth 2.1 client settings for a remote HTTP MCP server.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OAuthClientConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub callback_port: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<String>>,
}

impl fmt::Debug for OAuthClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthClientConfig")
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "<redacted>"),
            )
            .field("callback_port", &self.callback_port)
            .field("scopes", &self.scopes)
            .finish()
    }
}

/// Environment-expanded OAuth 2.1 client settings ready for an OAuth flow.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct ResolvedOAuthClientConfig {
    pub client_id: Option<String>,
    pub client_secret: Option<String>,
    pub callback_port: Option<u16>,
    pub scopes: Option<Vec<String>>,
}

impl fmt::Debug for ResolvedOAuthClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResolvedOAuthClientConfig")
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "<redacted>"),
            )
            .field("callback_port", &self.callback_port)
            .field("scopes", &self.scopes)
            .finish()
    }
}

impl OAuthClientConfig {
    /// Returns true when no OAuth client fields are set.
    pub fn is_empty(&self) -> bool {
        self.client_id
            .as_deref()
            .is_none_or(|s| s.trim().is_empty())
            && self
                .client_secret
                .as_deref()
                .is_none_or(|s| s.trim().is_empty())
            && self.callback_port.is_none()
            && self
                .scopes
                .as_ref()
                .is_none_or(|scopes| scopes.iter().all(|s| s.trim().is_empty()))
    }

    /// Trims string fields and drops empty entries; returns `None` when nothing remains.
    pub fn normalized(self) -> Option<Self> {
        let client_id = self
            .client_id
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        let client_secret = self
            .client_secret
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        let scopes = self
            .scopes
            .map(|items| {
                let mut seen = std::collections::BTreeSet::new();
                let mut cleaned = Vec::new();
                for item in items {
                    let trimmed = item.trim();
                    if !trimmed.is_empty() && seen.insert(trimmed.to_string()) {
                        cleaned.push(trimmed.to_string());
                    }
                }
                cleaned
            })
            .filter(|items| !items.is_empty());
        let out = Self {
            client_id,
            client_secret,
            callback_port: self.callback_port,
            scopes,
        };
        if out.is_empty() {
            None
        } else {
            Some(out)
        }
    }

    /// Validates OAuth client settings for `server_name`.
    pub fn validate(&self, server_name: &str) -> Result<(), McpConfigError> {
        if self.callback_port == Some(0) {
            return Err(McpConfigError::InvalidServer {
                name: server_name.to_string(),
                reason: "oauth.callback_port must be between 1 and 65535".to_string(),
            });
        }
        Ok(())
    }

    /// Returns whether a non-empty `client_secret` value is configured.
    pub fn has_client_secret(&self) -> bool {
        self.client_secret
            .as_deref()
            .is_some_and(|s| !s.trim().is_empty())
    }

    /// Expands `${ENV_VAR}` references in `client_id` and `client_secret`.
    pub fn resolve(
        &self,
        server_name: &str,
        env_lookup: &EnvLookup,
    ) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
        let client_id = match self.client_id.as_deref() {
            Some(raw) if !raw.trim().is_empty() => {
                let expanded = expand_env_vars(raw.trim(), env_lookup)
                    .map_err(|err| err.with_context(server_name, "oauth.client_id"))?;
                let trimmed = expanded.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            }
            _ => None,
        };
        let client_secret = match self.client_secret.as_deref() {
            Some(raw) if !raw.trim().is_empty() => {
                let expanded = expand_env_vars(raw.trim(), env_lookup)
                    .map_err(|err| err.with_context(server_name, "oauth.client_secret"))?;
                let trimmed = expanded.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            }
            _ => None,
        };
        let scopes = self
            .scopes
            .as_ref()
            .map(|items| {
                items
                    .iter()
                    .map(|s| s.trim())
                    .filter(|s| !s.is_empty())
                    .map(String::from)
                    .collect::<Vec<_>>()
            })
            .filter(|items| !items.is_empty());
        Ok(ResolvedOAuthClientConfig {
            client_id,
            client_secret,
            callback_port: self.callback_port,
            scopes,
        })
    }

    /// Expands `${ENV_VAR}` references using process environment and blyte's env file.
    pub fn resolve_from_system(
        &self,
        server_name: &str,
    ) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
        let lookup = EnvLookup::from_system()?;
        self.resolve(server_name, &lookup)
    }
}

/// Standard `mcpServers.<name>` entry compatible with Claude Code / Cursor configs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerConfig {
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "type")]
    pub transport: Option<TransportKind>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oauth: Option<OAuthClientConfig>,
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    #[serde(default)]
    pub approval: ApprovalPolicy,
}

impl ServerConfig {
    /// Creates a new stdio server configuration.
    pub fn stdio(
        command: impl Into<String>,
        args: Vec<String>,
        env: BTreeMap<String, String>,
        approval: ApprovalPolicy,
    ) -> Self {
        Self {
            transport: Some(TransportKind::Stdio),
            command: Some(command.into()),
            args,
            env,
            url: None,
            headers: BTreeMap::new(),
            oauth: None,
            enabled: true,
            approval,
        }
    }

    /// Creates a new Streamable HTTP server configuration.
    pub fn http(
        url: impl Into<String>,
        headers: BTreeMap<String, String>,
        approval: ApprovalPolicy,
    ) -> Self {
        Self {
            transport: Some(TransportKind::Http),
            command: None,
            args: Vec::new(),
            env: BTreeMap::new(),
            url: Some(url.into()),
            headers,
            oauth: None,
            enabled: true,
            approval,
        }
    }

    /// Attaches optional OAuth client settings to this server configuration.
    pub fn with_oauth(mut self, oauth: Option<OAuthClientConfig>) -> Self {
        self.oauth = oauth.and_then(OAuthClientConfig::normalized);
        self
    }

    /// Infers and validates the transport kind for this server entry.
    pub fn resolve_transport_kind(
        &self,
        server_name: &str,
    ) -> Result<TransportKind, McpConfigError> {
        let has_command = self
            .command
            .as_deref()
            .is_some_and(|c| !c.trim().is_empty());
        let has_url = self.url.as_deref().is_some_and(|u| !u.trim().is_empty());

        let kind = match self.transport {
            Some(TransportKind::Stdio) => {
                if !has_command {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "stdio server must specify a non-empty 'command'".to_string(),
                    });
                }
                if has_url {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "stdio server cannot also specify 'url'".to_string(),
                    });
                }
                TransportKind::Stdio
            }
            Some(TransportKind::Http) => {
                if !has_url {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "http server must specify a non-empty 'url'".to_string(),
                    });
                }
                if has_command {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "http server cannot also specify 'command'".to_string(),
                    });
                }
                TransportKind::Http
            }
            None => match (has_command, has_url) {
                (true, true) => {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "server specifies both 'command' and 'url'; remove one or set 'transport'".to_string(),
                    });
                }
                (true, false) => TransportKind::Stdio,
                (false, true) => TransportKind::Http,
                (false, false) => {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "server must specify either 'command' or 'url'".to_string(),
                    });
                }
            },
        };

        if kind == TransportKind::Http {
            let url = self.url.as_deref().unwrap_or("");
            if !url.starts_with("http://") && !url.starts_with("https://") {
                return Err(McpConfigError::InvalidServer {
                    name: server_name.to_string(),
                    reason: format!("http server url must start with http:// or https://: {url}"),
                });
            }
            if let Some(oauth) = &self.oauth {
                if oauth.callback_port == Some(0) {
                    return Err(McpConfigError::InvalidServer {
                        name: server_name.to_string(),
                        reason: "oauth.callback_port must be between 1 and 65535".to_string(),
                    });
                }
            }
        } else if self.oauth.as_ref().is_some_and(|o| !o.is_empty()) {
            return Err(McpConfigError::InvalidServer {
                name: server_name.to_string(),
                reason: "stdio server cannot specify 'oauth'".to_string(),
            });
        }

        Ok(kind)
    }

    /// Computes a deterministic SHA-256 fingerprint of the server's executable definition and approval policy.
    pub fn trust_fingerprint(&self) -> String {
        let mut hasher = Sha256::new();
        let update_str = |h: &mut Sha256, s: &str| {
            h.update((s.len() as u64).to_be_bytes());
            h.update(s.as_bytes());
        };
        let update_opt_str = |h: &mut Sha256, opt: Option<&str>| match opt {
            Some(s) => {
                h.update([1u8]);
                update_str(h, s);
            }
            None => h.update([0u8]),
        };

        update_opt_str(&mut hasher, self.transport.map(|t| t.as_str()));
        update_opt_str(&mut hasher, self.command.as_deref());
        hasher.update((self.args.len() as u64).to_be_bytes());
        for arg in &self.args {
            update_str(&mut hasher, arg);
        }
        hasher.update((self.env.len() as u64).to_be_bytes());
        for (k, v) in &self.env {
            update_str(&mut hasher, k);
            update_str(&mut hasher, v);
        }
        update_opt_str(&mut hasher, self.url.as_deref());
        hasher.update((self.headers.len() as u64).to_be_bytes());
        for (k, v) in &self.headers {
            update_str(&mut hasher, k);
            update_str(&mut hasher, v);
        }
        update_str(&mut hasher, self.approval.as_str());
        if let Some(oauth) = &self.oauth {
            if !oauth.is_empty() {
                hasher.update([1u8]);
                update_opt_str(&mut hasher, oauth.client_id.as_deref());
                update_opt_str(&mut hasher, oauth.client_secret.as_deref());
                match oauth.callback_port {
                    Some(port) => {
                        hasher.update([1u8]);
                        hasher.update(port.to_be_bytes());
                    }
                    None => hasher.update([0u8]),
                }
                match &oauth.scopes {
                    Some(scopes) => {
                        hasher.update([1u8]);
                        hasher.update((scopes.len() as u64).to_be_bytes());
                        for scope in scopes {
                            update_str(&mut hasher, scope);
                        }
                    }
                    None => hasher.update([0u8]),
                }
            }
        }

        let digest = hasher.finalize();
        format!("{digest:x}")
    }

    /// Short display target (URL for HTTP, command + args for stdio).
    pub fn target_display(&self) -> String {
        if let Some(url) = &self.url {
            return url.clone();
        }
        if let Some(cmd) = &self.command {
            if self.args.is_empty() {
                return cmd.clone();
            }
            return format!("{cmd} {}", self.args.join(" "));
        }
        String::new()
    }
}

/// Top-level `mcp.json` / `.mcp.json` file format.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct McpConfigFile {
    #[serde(rename = "mcpServers", default)]
    pub mcp_servers: BTreeMap<String, ServerConfig>,
}

/// Resolved, environment-expanded transport configuration ready to connect.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerTransport {
    Stdio {
        command: String,
        args: Vec<String>,
        env: BTreeMap<String, String>,
    },
    Http {
        url: String,
        headers: BTreeMap<String, String>,
    },
}

/// A validated MCP server loaded from user or project configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredServer {
    pub name: String,
    pub source: ServerSource,
    pub source_path: PathBuf,
    pub enabled: bool,
    pub approval: ApprovalPolicy,
    pub trusted: bool,
    pub transport_kind: TransportKind,
    pub config: ServerConfig,
}

impl ConfiguredServer {
    /// Expands `${ENV_VAR}` references in `env` or `headers` and returns the concrete transport.
    pub fn resolve_transport(
        &self,
        env_lookup: &EnvLookup,
    ) -> Result<ServerTransport, McpConfigError> {
        match self.transport_kind {
            TransportKind::Stdio => {
                let command =
                    self.config
                        .command
                        .clone()
                        .ok_or_else(|| McpConfigError::InvalidServer {
                            name: self.name.clone(),
                            reason: "stdio server missing 'command'".to_string(),
                        })?;
                let mut expanded_env = BTreeMap::new();
                for (k, v) in &self.config.env {
                    let expanded = expand_env_vars(v, env_lookup)
                        .map_err(|err| err.with_context(&self.name, &format!("env.{k}")))?;
                    expanded_env.insert(k.clone(), expanded);
                }
                Ok(ServerTransport::Stdio {
                    command,
                    args: self.config.args.clone(),
                    env: expanded_env,
                })
            }
            TransportKind::Http => {
                let url = self
                    .config
                    .url
                    .clone()
                    .ok_or_else(|| McpConfigError::InvalidServer {
                        name: self.name.clone(),
                        reason: "http server missing 'url'".to_string(),
                    })?;
                let mut expanded_headers = BTreeMap::new();
                for (k, v) in &self.config.headers {
                    let expanded = expand_env_vars(v, env_lookup)
                        .map_err(|err| err.with_context(&self.name, &format!("headers.{k}")))?;
                    expanded_headers.insert(k.clone(), expanded);
                }
                Ok(ServerTransport::Http {
                    url,
                    headers: expanded_headers,
                })
            }
        }
    }

    /// Expands `${ENV_VAR}` references using process environment and blyte's env file.
    pub fn resolve_transport_from_system(&self) -> Result<ServerTransport, McpConfigError> {
        let lookup = EnvLookup::from_system()?;
        self.resolve_transport(&lookup)
    }

    /// Expands `${ENV_VAR}` references in configured OAuth client settings, if any.
    pub fn resolve_oauth(
        &self,
        env_lookup: &EnvLookup,
    ) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
        match &self.config.oauth {
            Some(oauth) if !oauth.is_empty() => Ok(Some(oauth.resolve(&self.name, env_lookup)?)),
            _ => Ok(None),
        }
    }

    /// Expands `${ENV_VAR}` references in configured OAuth client settings using system env.
    pub fn resolve_oauth_from_system(
        &self,
    ) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
        let lookup = EnvLookup::from_system()?;
        self.resolve_oauth(&lookup)
    }
}

/// Errors returned while loading, validating, expanding, or saving MCP configuration.
#[derive(Debug)]
pub enum McpConfigError {
    ConfigDirUnavailable,
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    Parse {
        path: PathBuf,
        message: String,
    },
    InvalidServer {
        name: String,
        reason: String,
    },
    MissingEnvVar {
        server: Option<String>,
        field: Option<String>,
        var: String,
    },
    InvalidEnvSyntax {
        server: Option<String>,
        field: Option<String>,
        detail: String,
    },
    EnvFile(String),
    DuplicateServer(String),
    ServerNotFound(String),
}

impl McpConfigError {
    fn with_context(self, server: &str, field: &str) -> Self {
        match self {
            Self::MissingEnvVar { var, .. } => Self::MissingEnvVar {
                server: Some(server.to_string()),
                field: Some(field.to_string()),
                var,
            },
            Self::InvalidEnvSyntax { detail, .. } => Self::InvalidEnvSyntax {
                server: Some(server.to_string()),
                field: Some(field.to_string()),
                detail,
            },
            other => other,
        }
    }
}

impl fmt::Display for McpConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ConfigDirUnavailable => {
                write!(f, "cannot determine blyte config directory (neither XDG_CONFIG_HOME nor HOME is set)")
            }
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::Parse { path, message } => {
                write!(f, "failed to parse {}: {message}", path.display())
            }
            Self::InvalidServer { name, reason } => {
                write!(f, "invalid MCP server '{name}': {reason}")
            }
            Self::MissingEnvVar { server, field, var } => match (server, field) {
                (Some(s), Some(fld)) => write!(
                    f,
                    "MCP server '{s}' ({fld}) references missing environment variable '${{{var}}}'"
                ),
                _ => write!(f, "missing environment variable '${{{var}}}'"),
            },
            Self::InvalidEnvSyntax {
                server,
                field,
                detail,
            } => match (server, field) {
                (Some(s), Some(fld)) => {
                    write!(
                        f,
                        "MCP server '{s}' ({fld}) has invalid variable syntax: {detail}"
                    )
                }
                _ => write!(f, "invalid environment variable syntax: {detail}"),
            },
            Self::EnvFile(msg) => write!(f, "failed to load blyte env file: {msg}"),
            Self::DuplicateServer(name) => {
                write!(
                    f,
                    "MCP server '{name}' already exists (pass --replace to overwrite)"
                )
            }
            Self::ServerNotFound(name) => write!(f, "MCP server '{name}' not found"),
        }
    }
}

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

/// Source for `${ENV_VAR}` expansion combining process environment and blyte's env file.
#[derive(Debug, Clone, Default)]
pub struct EnvLookup {
    process_env: Option<BTreeMap<String, String>>,
    file_env: BTreeMap<String, String>,
}

impl EnvLookup {
    /// Builds an `EnvLookup` reading from the live process environment and blyte's default env file.
    pub fn from_system() -> Result<Self, McpConfigError> {
        let mut file_env = BTreeMap::new();
        if let Some(path) = crate::env_file::default_path() {
            file_env = read_env_file_map(&path)?;
        }
        Ok(Self {
            process_env: None,
            file_env,
        })
    }

    /// Builds an `EnvLookup` reading from live process environment and a specific env file path.
    pub fn from_process_and_file(env_file_path: &Path) -> Result<Self, McpConfigError> {
        let file_env = read_env_file_map(env_file_path)?;
        Ok(Self {
            process_env: None,
            file_env,
        })
    }

    /// Builds an isolated `EnvLookup` from explicit maps (useful for deterministic testing).
    pub fn from_maps(
        process_env: BTreeMap<String, String>,
        file_env: BTreeMap<String, String>,
    ) -> Self {
        Self {
            process_env: Some(process_env),
            file_env,
        }
    }

    /// Resolves a variable name: process environment takes precedence over env file.
    pub fn get(&self, name: &str) -> Option<String> {
        match &self.process_env {
            Some(map) => {
                if let Some(val) = map.get(name) {
                    return Some(val.clone());
                }
            }
            None => {
                if let Ok(val) = std::env::var(name) {
                    return Some(val);
                }
            }
        }
        self.file_env.get(name).cloned()
    }
}

fn read_env_file_map(path: &Path) -> Result<BTreeMap<String, String>, McpConfigError> {
    let meta = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
        Err(e) => {
            return Err(McpConfigError::Io {
                path: path.to_path_buf(),
                source: e,
            });
        }
    };
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if meta.permissions().mode() & 0o077 != 0 {
            return Err(McpConfigError::EnvFile(format!(
                "{} can be read by other users, so it was not loaded; run: chmod 600 {}",
                path.display(),
                path.display()
            )));
        }
    }
    #[cfg(not(unix))]
    let _ = meta;

    let text = std::fs::read_to_string(path).map_err(|source| McpConfigError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let mut map = BTreeMap::new();
    for (k, v) in crate::env_file::parse(&text) {
        map.insert(k, v);
    }
    Ok(map)
}

/// Expands all `${ENV_VAR}` placeholders in `input` using `lookup`.
/// Returns an error if syntax is malformed or any referenced variable is missing.
pub fn expand_env_vars(input: &str, lookup: &EnvLookup) -> Result<String, McpConfigError> {
    let mut out = String::with_capacity(input.len());
    let mut rest = input;
    while let Some(idx) = rest.find("${") {
        out.push_str(&rest[..idx]);
        let after_open = &rest[idx + 2..];
        let Some(end) = after_open.find('}') else {
            return Err(McpConfigError::InvalidEnvSyntax {
                server: None,
                field: None,
                detail: format!("unclosed '${{' in '{input}'"),
            });
        };
        let var_name = &after_open[..end];
        if !is_valid_env_name(var_name) {
            return Err(McpConfigError::InvalidEnvSyntax {
                server: None,
                field: None,
                detail: format!("invalid environment variable name '${{{var_name}}}'"),
            });
        }
        let value = lookup
            .get(var_name)
            .ok_or_else(|| McpConfigError::MissingEnvVar {
                server: None,
                field: None,
                var: var_name.to_string(),
            })?;
        out.push_str(&value);
        rest = &after_open[end + 1..];
    }
    out.push_str(rest);
    Ok(out)
}

fn is_valid_env_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Returns blyte's user configuration directory (`$XDG_CONFIG_HOME/blyte` or `~/.config/blyte`).
pub fn user_config_dir() -> Result<PathBuf, McpConfigError> {
    if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
        return Ok(PathBuf::from(x).join("blyte"));
    }
    std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .map(|h| PathBuf::from(h).join(".config/blyte"))
        .ok_or(McpConfigError::ConfigDirUnavailable)
}

/// Returns the user-level MCP configuration file path (`<config_dir>/mcp.json`).
pub fn user_config_path() -> Result<PathBuf, McpConfigError> {
    Ok(user_config_dir()?.join("mcp.json"))
}

/// Returns the user-level project-server trust store path (`<config_dir>/mcp-trust.json`).
pub fn trust_store_path() -> Result<PathBuf, McpConfigError> {
    Ok(user_config_dir()?.join("mcp-trust.json"))
}

/// Returns the project-level `.mcp.json` path under `project_root`.
pub fn project_config_path(project_root: &Path) -> PathBuf {
    project_root.join(".mcp.json")
}

/// Loads a single `mcp.json` or `.mcp.json` file.
/// A missing file returns an empty configuration; unreadable or malformed files return an error.
pub fn load_config_file(path: &Path) -> Result<McpConfigFile, McpConfigError> {
    let text = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(McpConfigFile::default()),
        Err(source) => {
            return Err(McpConfigError::Io {
                path: path.to_path_buf(),
                source,
            });
        }
    };
    let parsed: McpConfigFile = serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
        path: path.to_path_buf(),
        message: e.to_string(),
    })?;
    for (name, cfg) in &parsed.mcp_servers {
        if name.trim().is_empty() {
            return Err(McpConfigError::InvalidServer {
                name: name.clone(),
                reason: "server name cannot be empty".to_string(),
            });
        }
        cfg.resolve_transport_kind(name)?;
    }
    Ok(parsed)
}

/// Writes `config` to `path` with mode `0600` on Unix, creating parent directories if needed.
pub fn save_config_file(path: &Path, config: &McpConfigFile) -> Result<(), McpConfigError> {
    let mut rendered = serde_json::to_string_pretty(config).map_err(|e| McpConfigError::Parse {
        path: path.to_path_buf(),
        message: e.to_string(),
    })?;
    rendered.push('\n');
    write_restricted_file(path, rendered.as_bytes())
}

fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<(), McpConfigError> {
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent).map_err(|source| McpConfigError::Io {
            path: parent.to_path_buf(),
            source,
        })?;
    }

    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)
            .map_err(|source| McpConfigError::Io {
                path: path.to_path_buf(),
                source,
            })?;
        file.write_all(bytes).map_err(|source| McpConfigError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
            |source| McpConfigError::Io {
                path: path.to_path_buf(),
                source,
            },
        )?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(path, bytes).map_err(|source| McpConfigError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    }

    Ok(())
}

/// Persistent record of explicitly approved project-level MCP servers.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectTrustStore {
    #[serde(default)]
    pub projects: BTreeMap<String, BTreeMap<String, String>>,
}

impl ProjectTrustStore {
    /// Loads the trust store from `path`. Missing file means no trusted project servers.
    pub fn load(path: &Path) -> Result<Self, McpConfigError> {
        let text = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Self::default()),
            Err(source) => {
                return Err(McpConfigError::Io {
                    path: path.to_path_buf(),
                    source,
                });
            }
        };
        serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
            path: path.to_path_buf(),
            message: e.to_string(),
        })
    }

    /// Saves the trust store to `path` with mode `0600` on Unix.
    pub fn save(&self, path: &Path) -> Result<(), McpConfigError> {
        let mut rendered =
            serde_json::to_string_pretty(self).map_err(|e| McpConfigError::Parse {
                path: path.to_path_buf(),
                message: e.to_string(),
            })?;
        rendered.push('\n');
        write_restricted_file(path, rendered.as_bytes())
    }

    /// Checks whether `server_name` in `project_root` is explicitly trusted for its current config.
    pub fn is_trusted(
        &self,
        project_root: &Path,
        server_name: &str,
        config: &ServerConfig,
    ) -> Result<bool, McpConfigError> {
        let key = project_key(project_root)?;
        let expected = config.trust_fingerprint();
        Ok(self
            .projects
            .get(&key)
            .and_then(|servers| servers.get(server_name))
            .is_some_and(|stored| stored == &expected))
    }

    /// Records explicit user approval for a project-level server's current configuration.
    pub fn trust(
        &mut self,
        project_root: &Path,
        server_name: &str,
        config: &ServerConfig,
    ) -> Result<(), McpConfigError> {
        let key = project_key(project_root)?;
        self.projects
            .entry(key)
            .or_default()
            .insert(server_name.to_string(), config.trust_fingerprint());
        Ok(())
    }

    /// Revokes trust for a project-level server.
    pub fn revoke(
        &mut self,
        project_root: &Path,
        server_name: &str,
    ) -> Result<bool, McpConfigError> {
        let key = project_key(project_root)?;
        let Some(servers) = self.projects.get_mut(&key) else {
            return Ok(false);
        };
        let removed = servers.remove(server_name).is_some();
        if servers.is_empty() {
            self.projects.remove(&key);
        }
        Ok(removed)
    }
}

fn project_key(project_root: &Path) -> Result<String, McpConfigError> {
    let canonical = std::fs::canonicalize(project_root).map_err(|source| McpConfigError::Io {
        path: project_root.to_path_buf(),
        source,
    })?;
    Ok(canonical.to_string_lossy().into_owned())
}

/// Loads all configured servers from user config and optional project `.mcp.json`,
/// tagging each with its source and trust status.
/// User servers are always trusted; project servers default to untrusted unless present
/// with a matching fingerprint in `trust_path`.
pub fn load_configured_servers(
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
) -> Result<Vec<ConfiguredServer>, McpConfigError> {
    let user_file = load_config_file(user_path)?;
    let mut servers = Vec::new();
    let mut seen_names = std::collections::BTreeSet::new();

    for (name, config) in user_file.mcp_servers {
        let transport_kind = config.resolve_transport_kind(&name)?;
        seen_names.insert(name.clone());
        servers.push(ConfiguredServer {
            name,
            source: ServerSource::User,
            source_path: user_path.to_path_buf(),
            enabled: config.enabled,
            approval: config.approval,
            trusted: true,
            transport_kind,
            config,
        });
    }

    if let Some(root) = project_root {
        let proj_path = project_config_path(root);
        let proj_file = load_config_file(&proj_path)?;
        if !proj_file.mcp_servers.is_empty() {
            let trust_store = ProjectTrustStore::load(trust_path)?;
            for (name, config) in proj_file.mcp_servers {
                if seen_names.contains(&name) {
                    continue;
                }
                let transport_kind = config.resolve_transport_kind(&name)?;
                let trusted = trust_store.is_trusted(root, &name, &config)?;
                servers.push(ConfiguredServer {
                    name,
                    source: ServerSource::Project,
                    source_path: proj_path.clone(),
                    enabled: config.enabled,
                    approval: config.approval,
                    trusted,
                    transport_kind,
                    config,
                });
            }
        }
    }

    servers.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(servers)
}

/// Adds or replaces a server entry in `user_path`.
pub fn add_user_server(
    user_path: &Path,
    name: &str,
    config: ServerConfig,
    replace: bool,
) -> Result<(), McpConfigError> {
    validate_server_name(name)?;
    config.resolve_transport_kind(name)?;
    let mut file = load_config_file(user_path)?;
    if !replace && file.mcp_servers.contains_key(name) {
        return Err(McpConfigError::DuplicateServer(name.to_string()));
    }
    file.mcp_servers.insert(name.to_string(), config);
    save_config_file(user_path, &file)
}

/// Removes a server entry from `user_path`. Returns `ServerNotFound` if absent.
pub fn remove_user_server(user_path: &Path, name: &str) -> Result<(), McpConfigError> {
    let mut file = load_config_file(user_path)?;
    if file.mcp_servers.remove(name).is_none() {
        return Err(McpConfigError::ServerNotFound(name.to_string()));
    }
    save_config_file(user_path, &file)
}

/// Validates a server name for `blyte mcp add`.
pub fn validate_server_name(name: &str) -> Result<(), McpConfigError> {
    if name.trim().is_empty() {
        return Err(McpConfigError::InvalidServer {
            name: name.to_string(),
            reason: "server name cannot be empty".to_string(),
        });
    }
    if name.chars().any(|c| c.is_whitespace()) {
        return Err(McpConfigError::InvalidServer {
            name: name.to_string(),
            reason: "server name cannot contain whitespace".to_string(),
        });
    }
    if name.contains("__") {
        return Err(McpConfigError::InvalidServer {
            name: name.to_string(),
            reason: "server name cannot contain '__'".to_string(),
        });
    }
    Ok(())
}