yapi-core 0.4.2

Coding agent core: sessions, compaction, settings, resources, built-in tools, system prompt, packages, extension runner and MCP. An internal library of yapi, with no stable API.
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
//! `mcp.json`: the MCP servers of the agent directory and, for trusted
//! projects, of `<project>/.yapi/mcp.json`, in the `mcpServers` shape other MCP
//! clients share. Project entries replace global ones of the same name. Port
//! of `extensions/mcp/config.ts` and `core/mcp-servers.ts` in pi `v1.0.0`.

use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use reqwest::Url;
use serde_json::{Map, Value};
use yapi_types::config::ConfigFile;
use yapi_types::extension_event::RegisteredMcpServer;

use crate::config::PROJECT_DIR;

/// pi's `McpExposure`: how an MCP server's tools reach the model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum McpExposure {
    /// Called from codemode scripts. The default.
    Codemode,
    /// Declared once `tool_search` loads them.
    Deferred,
    /// Declared to the model like built-in tools.
    Direct,
    /// Unreachable.
    Hidden,
}

impl McpExposure {
    /// The configuration name.
    pub fn as_str(self) -> &'static str {
        match self {
            McpExposure::Codemode => "codemode",
            McpExposure::Deferred => "deferred",
            McpExposure::Direct => "direct",
            McpExposure::Hidden => "hidden",
        }
    }

    /// Parses a configuration name or its alias.
    fn parse(value: &Value) -> Option<McpExposure> {
        match value.as_str()? {
            "codemode" | "codemode-deferred" => Some(McpExposure::Codemode),
            "deferred" => Some(McpExposure::Deferred),
            "direct" => Some(McpExposure::Direct),
            "hidden" => Some(McpExposure::Hidden),
            _ => None,
        }
    }

    /// The tool exposure: `codemode` tools are deferred tools that codemode
    /// reaches. The two differ only in which discovery tool is activated.
    pub fn tool_exposure(self) -> crate::tools::Exposure {
        use crate::tools::Exposure;
        match self {
            McpExposure::Codemode | McpExposure::Deferred => Exposure::Deferred,
            McpExposure::Direct => Exposure::Direct,
            McpExposure::Hidden => Exposure::Hidden,
        }
    }
}

/// How to reach a server.
#[derive(Clone, Debug, PartialEq)]
pub enum ServerTransport {
    /// A process speaking JSON-RPC on stdin and stdout.
    Stdio {
        /// The program.
        command: String,
        /// Its arguments.
        args: Vec<String>,
        /// Environment values, which may reference variables or commands.
        env: IndexMap<String, String>,
        /// Working directory, relative to the session's.
        cwd: Option<String>,
    },
    /// A streamable HTTP endpoint.
    Http {
        /// The URL.
        url: String,
        /// Header values, which may reference variables or commands.
        headers: IndexMap<String, String>,
        /// The `/login` provider whose token is sent.
        auth_provider: Option<String>,
        /// OAuth client settings.
        oauth: Option<OAuthConfig>,
    },
}

/// pi's `McpOAuthConfig`: OAuth client settings for servers that do not
/// support dynamic client registration.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OAuthConfig {
    /// Pre-registered client id.
    pub client_id: Option<String>,
    /// Client secret, which may reference variables or commands.
    pub client_secret: Option<String>,
    /// Port of the loopback callback server.
    pub callback_port: Option<u16>,
    /// Redirect URI registered for `client_id`.
    pub callback_url: Option<String>,
    /// Scopes to request, separated by spaces.
    pub scope: Option<String>,
    /// `client_name` for dynamic client registration.
    pub client_name: Option<String>,
    /// Authorization server metadata document to use instead of discovery.
    pub auth_server_metadata_url: Option<String>,
}

impl ServerTransport {
    /// Whether the server would sign in with OAuth: HTTP without an
    /// `Authorization` header or provider auth.
    pub fn uses_oauth(&self) -> bool {
        matches!(self, ServerTransport::Http { headers, auth_provider: None, .. }
            if !headers.keys().any(|name| name.eq_ignore_ascii_case("authorization")))
    }
}

/// One validated server entry.
#[derive(Clone, Debug, PartialEq)]
pub struct ServerConfig {
    /// Transport settings.
    pub transport: ServerTransport,
    /// Default exposure of its tools.
    pub exposure: Option<McpExposure>,
    /// What the server offers, in a sentence.
    pub description: Option<String>,
    /// Exposure of single tools by name or `*` pattern, in file order.
    pub tool_exposure: IndexMap<String, McpExposure>,
    /// `false` keeps the entry without connecting.
    pub enabled: Option<bool>,
    /// Per-request timeout in seconds.
    pub timeout: Option<f64>,
}

impl ServerConfig {
    /// The server's exposure, `codemode` by default.
    pub fn exposure(&self) -> McpExposure {
        self.exposure.unwrap_or(McpExposure::Codemode)
    }

    /// Whether it connects.
    pub fn is_enabled(&self) -> bool {
        self.enabled != Some(false)
    }

    /// pi's `getMcpToolExposure`: an exact `toolExposure` entry, else the
    /// first matching pattern, else the server's exposure.
    pub fn tool_exposure(&self, tool: &str) -> McpExposure {
        if let Some(exposure) = self.tool_exposure.get(tool) {
            return *exposure;
        }
        for (pattern, exposure) in &self.tool_exposure {
            if pattern.contains('*') && glob(pattern, tool) {
                return *exposure;
            }
        }
        self.exposure()
    }

    /// Every exposure its tools can have, known before it connects.
    pub fn exposures(&self) -> Vec<McpExposure> {
        let mut exposures = vec![self.exposure()];
        for exposure in self.tool_exposure.values() {
            if !exposures.contains(exposure) {
                exposures.push(*exposure);
            }
        }
        exposures
    }
}

/// pi's `toolPatternRegExp`: `*` matches any characters.
fn glob(pattern: &str, text: &str) -> bool {
    let parts: Vec<String> = pattern.split('*').map(regex_lite::escape).collect();
    regex_lite::Regex::new(&format!("^{}$", parts.join(".*")))
        .is_ok_and(|regex| regex.is_match(text))
}

/// Which file defined a server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
    /// The agent directory's `mcp.json`.
    Global,
    /// The project's `mcp.json`.
    Project,
    /// Registered by the extension at `source` with `pi.registerMcpServer`.
    Extension,
}

impl Scope {
    /// pi's name for the scope.
    pub fn as_str(self) -> &'static str {
        match self {
            Scope::Global => "global",
            Scope::Project => "project",
            Scope::Extension => "extension",
        }
    }
}

/// A configured server.
#[derive(Clone, Debug, PartialEq)]
pub struct ServerEntry {
    /// Its name.
    pub name: String,
    /// Its settings.
    pub config: ServerConfig,
    /// The file that defined it.
    pub source: PathBuf,
    /// Which file that is.
    pub scope: Scope,
}

impl ServerEntry {
    /// pi's `describeTransport`: the URL, or the command line.
    pub fn describe_transport(&self) -> String {
        match &self.config.transport {
            ServerTransport::Http { url, .. } => url.clone(),
            ServerTransport::Stdio { command, args, .. } => std::iter::once(command)
                .chain(args)
                .cloned()
                .collect::<Vec<_>>()
                .join(" "),
        }
    }
}

/// Everything `mcp.json` files configure, and their problems.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LoadedConfig {
    /// Servers in definition order.
    pub servers: Vec<ServerEntry>,
    /// Whether codemode is activated for `codemode` servers.
    pub auto_enable_codemode: Option<bool>,
    /// Problems, each prefixed with its file.
    pub errors: Vec<String>,
}

/// `mcp__<server>` with `-` as `_`, the prefix of the server's tool names.
pub fn namespace(server: &str) -> String {
    format!("mcp__{}", server.replace('-', "_"))
}

/// pi's checks of server `name`, which an extension registers, against the
/// servers that extensions of other runtimes registered: neither the name
/// nor its tools' namespace may be theirs. The error is pi's.
pub fn check_registration<'a, I>(others: I, name: &str) -> Result<(), String>
where
    I: IntoIterator<Item = &'a RegisteredMcpServer>,
    I::IntoIter: Clone,
{
    let mut others = others.into_iter();
    if let Some(theirs) = others.clone().find(|server| server.name == name) {
        return Err(format!(
            "MCP server \"{name}\" is already registered by extension \"{}\"",
            theirs.extension_path
        ));
    }
    let ours = namespace(name);
    if let Some(theirs) = others.find(|server| namespace(&server.name) == ours) {
        return Err(format!(
            "MCP server \"{name}\" conflicts with registered server \"{}\"",
            theirs.name
        ));
    }
    Ok(())
}

const LOOPBACK_HOSTS: [&str; 3] = ["localhost", "127.0.0.1", "[::1]"];

/// The host as JavaScript's `URL.hostname` gives it, IPv6 in brackets.
fn host(url: &Url) -> String {
    url.host_str().unwrap_or_default().to_owned()
}

fn string_map(value: &Value) -> Option<IndexMap<String, String>> {
    value
        .as_object()?
        .iter()
        .map(|(key, value)| Some((key.clone(), value.as_str()?.to_owned())))
        .collect()
}

fn validate_oauth(value: &Value) -> Option<String> {
    let Some(oauth) = value.as_object() else {
        return Some("oauth must be an object".into());
    };
    let string = |key: &str| oauth.get(key).is_none_or(Value::is_string);
    if !string("clientId") {
        return Some("oauth.clientId must be a string".into());
    }
    if !string("clientSecret") {
        return Some("oauth.clientSecret must be a string".into());
    }
    let port = oauth.get("callbackPort");
    if let Some(port) = port
        && !port
            .as_f64()
            .is_some_and(|port| port.fract() == 0.0 && (1.0..=65535.0).contains(&port))
    {
        return Some("oauth.callbackPort must be a port number".into());
    }
    if let Some(callback) = oauth.get("callbackUrl") {
        let url = callback.as_str().and_then(|text| Url::parse(text).ok());
        let loopback = url.as_ref().is_some_and(|url| {
            url.scheme() == "http"
                && LOOPBACK_HOSTS.contains(&host(url).as_str())
                && url.query().is_none()
                && url.fragment().is_none()
        });
        let Some(url) = url.filter(|_| loopback) else {
            return Some("oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment".into());
        };
        if let (Some(url_port), Some(port)) = (url.port(), port.and_then(Value::as_f64))
            && f64::from(url_port) != port
        {
            return Some("oauth.callbackUrl and oauth.callbackPort name different ports".into());
        }
    }
    if !string("scope") {
        return Some("oauth.scope must be a string".into());
    }
    if let Some(name) = oauth.get("clientName")
        && !name.as_str().is_some_and(|name| !name.trim().is_empty())
    {
        return Some("oauth.clientName must be a non-empty string".into());
    }
    if let Some(metadata) = oauth.get("authServerMetadataUrl") {
        let url = metadata.as_str().and_then(|text| Url::parse(text).ok());
        let allowed = url.is_some_and(|url| {
            url.scheme() == "https"
                || (url.scheme() == "http" && LOOPBACK_HOSTS.contains(&host(&url).as_str()))
        });
        if !allowed {
            return Some("oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]".into());
        }
    }
    None
}

/// pi's `validateMcpServerConfig`: the entry, or an error message.
pub fn validate_server(name: &str, raw: &Value) -> Result<ServerConfig, String> {
    let valid_name = !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    if !valid_name {
        return Err(format!(
            "invalid server name \"{name}\" (use letters, digits, \"_\" and \"-\")"
        ));
    }
    let Some(value) = raw.as_object() else {
        return Err(format!("server \"{name}\" must be an object"));
    };
    let exposures = "\"codemode\", \"deferred\", \"direct\", \"hidden\"";
    let exposure = match value.get("exposure") {
        None => None,
        Some(raw) => Some(
            McpExposure::parse(raw)
                .ok_or_else(|| format!("server \"{name}\": exposure must be one of {exposures}"))?,
        ),
    };
    let mut tool_exposure = IndexMap::new();
    if let Some(raw) = value.get("toolExposure") {
        let Some(entries) = raw.as_object() else {
            return Err(format!(
                "server \"{name}\": toolExposure must map tool names to exposures"
            ));
        };
        for (tool, entry) in entries {
            let exposure = McpExposure::parse(entry).ok_or_else(|| {
                format!("server \"{name}\": toolExposure \"{tool}\" must be one of {exposures}")
            })?;
            tool_exposure.insert(tool.clone(), exposure);
        }
    }
    let enabled = match value.get("enabled") {
        None => None,
        Some(Value::Bool(enabled)) => Some(*enabled),
        Some(_) => return Err(format!("server \"{name}\": enabled must be a boolean")),
    };
    let description = match value.get("description") {
        None => None,
        Some(Value::String(text)) => Some(text.clone()),
        Some(_) => return Err(format!("server \"{name}\": description must be a string")),
    };
    let timeout = match value.get("timeout") {
        None => None,
        Some(raw) => match raw.as_f64() {
            Some(seconds) if seconds > 0.0 => Some(seconds),
            _ => {
                return Err(format!(
                    "server \"{name}\": timeout must be a positive number of seconds"
                ));
            }
        },
    };
    let kind = value.get("type").and_then(Value::as_str);
    if kind == Some("sse") {
        return Err(format!(
            "server \"{name}\": legacy SSE transport is not supported; use the streamable HTTP URL"
        ));
    }
    let base = |transport| ServerConfig {
        transport,
        exposure,
        description: description.clone(),
        tool_exposure: tool_exposure.clone(),
        enabled,
        timeout,
    };
    let kind_is = |names: &[&str]| {
        value.get("type").is_none() || kind.is_some_and(|kind| names.contains(&kind))
    };
    if let Some(url) = value.get("url").and_then(Value::as_str)
        && kind_is(&["http", "streamable-http"])
    {
        let parsed = Url::parse(url)
            .ok()
            .filter(|url| url.scheme() == "http" || url.scheme() == "https")
            .ok_or_else(|| format!("server \"{name}\": url must be an http or https URL"))?;
        let headers = match value.get("headers") {
            None => IndexMap::new(),
            Some(raw) => string_map(raw)
                .ok_or_else(|| format!("server \"{name}\": headers must map names to strings"))?,
        };
        if let Some(oauth) = value.get("oauth")
            && let Some(problem) = validate_oauth(oauth)
        {
            return Err(format!("server \"{name}\": {problem}"));
        }
        let oauth = value.get("oauth").map(|oauth| {
            let string = |key: &str| oauth.get(key).and_then(Value::as_str).map(str::to_owned);
            OAuthConfig {
                client_id: string("clientId"),
                client_secret: string("clientSecret"),
                // Validated as a whole number from 1 to 65535.
                callback_port: oauth
                    .get("callbackPort")
                    .and_then(Value::as_f64)
                    .map(|port| port as u16),
                callback_url: string("callbackUrl"),
                scope: string("scope"),
                client_name: string("clientName"),
                auth_server_metadata_url: string("authServerMetadataUrl"),
            }
        });
        let auth_provider = match value.get("auth") {
            None => None,
            Some(auth) => {
                let provider = auth
                    .get("provider")
                    .and_then(Value::as_str)
                    .filter(|provider| !provider.is_empty())
                    .ok_or_else(|| {
                        format!("server \"{name}\": auth.provider must be a provider name")
                    })?;
                if parsed.scheme() != "https" && !LOOPBACK_HOSTS.contains(&host(&parsed).as_str()) {
                    return Err(format!(
                        "server \"{name}\": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]"
                    ));
                }
                Some(provider.to_owned())
            }
        };
        return Ok(base(ServerTransport::Http {
            url: url.to_owned(),
            headers,
            auth_provider,
            oauth,
        }));
    }
    if let Some(command) = value.get("command").and_then(Value::as_str)
        && kind_is(&["stdio"])
    {
        let args = match value.get("args") {
            None => Vec::new(),
            Some(Value::Array(items)) if items.iter().all(Value::is_string) => items
                .iter()
                .filter_map(|item| item.as_str().map(str::to_owned))
                .collect(),
            Some(_) => {
                return Err(format!(
                    "server \"{name}\": args must be an array of strings"
                ));
            }
        };
        let env = match value.get("env") {
            None => IndexMap::new(),
            Some(raw) => string_map(raw)
                .ok_or_else(|| format!("server \"{name}\": env must map names to strings"))?,
        };
        let cwd = match value.get("cwd") {
            None => None,
            Some(Value::String(cwd)) => Some(cwd.clone()),
            Some(_) => return Err(format!("server \"{name}\": cwd must be a string")),
        };
        return Ok(base(ServerTransport::Stdio {
            command: command.to_owned(),
            args,
            env,
            cwd,
        }));
    }
    Err(format!(
        "server \"{name}\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)"
    ))
}

fn read_file(path: &Path, scope: Scope, keep: Option<&[String]>, loaded: &mut LoadedConfig) {
    let Ok(text) = std::fs::read_to_string(path) else {
        return;
    };
    let parsed: Map<String, Value> = match serde_json::from_str::<Value>(&text) {
        Ok(Value::Object(parsed)) if parsed.get("mcpServers").is_none_or(Value::is_object) => {
            parsed
        }
        Ok(_) => {
            loaded.errors.push(format!(
                "{}: expected an object with an \"mcpServers\" object",
                path.display()
            ));
            return;
        }
        Err(error) => {
            loaded.errors.push(format!("{}: {error}", path.display()));
            return;
        }
    };
    match parsed.get("autoEnableCodemode") {
        None => {}
        Some(Value::Bool(value)) => loaded.auto_enable_codemode = Some(*value),
        Some(_) => loaded.errors.push(format!(
            "{}: autoEnableCodemode must be a boolean",
            path.display()
        )),
    }
    let empty = Map::new();
    let servers = parsed
        .get("mcpServers")
        .and_then(Value::as_object)
        .unwrap_or(&empty);
    // A server a project-only run leaves out is never looked at, so it can
    // neither clash with a kept one nor report problems.
    let kept = |name: &str| {
        keep.is_none_or(|keep| {
            keep.iter()
                .any(|pattern| crate::glob::matches(pattern, name))
        })
    };
    for (name, raw) in servers.iter().filter(|(name, _)| kept(name)) {
        let config = match validate_server(name, raw) {
            Ok(config) => config,
            Err(problem) => {
                loaded.errors.push(format!("{}: {problem}", path.display()));
                continue;
            }
        };
        // Names that differ only in `-` and `_` would share a namespace.
        if let Some(clash) = loaded
            .servers
            .iter()
            .find(|other| other.name != *name && namespace(&other.name) == namespace(name))
        {
            loaded.errors.push(format!(
                "{}: server \"{name}\" conflicts with \"{}\"",
                path.display(),
                clash.name
            ));
            continue;
        }
        if scope == Scope::Project
            && matches!(
                config.transport,
                ServerTransport::Http {
                    auth_provider: Some(_),
                    ..
                }
            )
        {
            loaded.errors.push(format!(
                "{}: server \"{name}\": auth is only allowed in the global mcp.json",
                path.display()
            ));
            continue;
        }
        let entry = ServerEntry {
            name: name.clone(),
            config,
            source: path.to_path_buf(),
            scope,
        };
        match loaded.servers.iter_mut().find(|other| other.name == *name) {
            Some(existing) => *existing = entry,
            None => loaded.servers.push(entry),
        }
    }
}

/// Loads the global and, when trusted, the `mcp.json` of the project in
/// `project_dir`. Disabled servers are included. With `keep`, as in a
/// project-only run, the global file gives only the servers whose names
/// match its patterns.
pub fn load(
    agent_dir: &Path,
    project_dir: &Path,
    project_trusted: bool,
    keep: Option<&[String]>,
) -> LoadedConfig {
    let mut loaded = LoadedConfig::default();
    let name = ConfigFile::Mcp.file_name();
    read_file(&agent_dir.join(name), Scope::Global, keep, &mut loaded);
    if project_trusted {
        read_file(
            &project_dir.join(PROJECT_DIR).join(name),
            Scope::Project,
            None,
            &mut loaded,
        );
    }
    loaded
}

/// pi's `resolveExposureAliases`: `raw` with exposure aliases, in
/// `exposure` and `toolExposure`, replaced by their current names.
pub fn resolve_exposure_aliases(raw: &Value) -> Value {
    let canonical = |value: &Value| match McpExposure::parse(value) {
        Some(exposure) => Value::String(exposure.as_str().to_owned()),
        None => value.clone(),
    };
    let mut resolved = raw.clone();
    if let Some(object) = resolved.as_object_mut() {
        if let Some(exposure) = object.get_mut("exposure") {
            *exposure = canonical(exposure);
        }
        if let Some(Value::Object(tools)) = object.get_mut("toolExposure") {
            for value in tools.values_mut() {
                *value = canonical(value);
            }
        }
    }
    resolved
}

/// pi's `addMcpServerConfig`: adds `config` as server `name` to the
/// `mcp.json` at `path`, creating the file when missing. Returns whether an
/// entry of that name was replaced.
pub fn add_server_config(path: &Path, name: &str, config: Value) -> Result<bool, String> {
    let mut replaced = false;
    edit_servers(path, |document| {
        let servers = document
            .entry("mcpServers")
            .or_insert_with(|| Value::Object(Map::new()));
        if let Value::Object(servers) = servers {
            replaced = servers.insert(name.to_owned(), config).is_some();
        }
        true
    })?;
    Ok(replaced)
}

/// pi's `removeMcpServerConfig`: removes server `name` from the `mcp.json`
/// at `path`. Returns false when the file does not define it.
pub fn remove_server_config(path: &Path, name: &str) -> Result<bool, String> {
    if !path.exists() {
        return Ok(false);
    }
    let mut removed = false;
    edit_servers(path, |document| {
        removed = document
            .get_mut("mcpServers")
            .and_then(Value::as_object_mut)
            .is_some_and(|servers| servers.shift_remove(name).is_some());
        removed
    })?;
    Ok(removed)
}

/// pi's `McpServerConfigPatch`: a setting `/mcp` changes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConfigPatch {
    /// `enabled`.
    Enabled(bool),
    /// `exposure`.
    Exposure(McpExposure),
}

impl ConfigPatch {
    /// Applies the patch to a loaded config.
    pub fn apply(self, config: &mut ServerConfig) {
        match self {
            ConfigPatch::Enabled(enabled) => config.enabled = Some(enabled),
            ConfigPatch::Exposure(exposure) => config.exposure = Some(exposure),
        }
    }
}

/// pi's `updateMcpServerConfig`: changes one setting of server `name` in the
/// `mcp.json` at `path`. The defaults, `enabled: true` and
/// `exposure: "codemode"`, remove the key.
pub fn update_server_config(path: &Path, name: &str, patch: ConfigPatch) -> Result<(), String> {
    let mut found = false;
    edit_servers(path, |document| {
        let Some(Value::Object(server)) = document
            .get_mut("mcpServers")
            .and_then(|servers| servers.get_mut(name))
        else {
            return false;
        };
        found = true;
        let (key, value) = match patch {
            ConfigPatch::Enabled(enabled) => ("enabled", (!enabled).then_some(Value::Bool(false))),
            ConfigPatch::Exposure(exposure) => (
                "exposure",
                (exposure != McpExposure::Codemode).then(|| Value::from(exposure.as_str())),
            ),
        };
        match value {
            Some(value) => {
                server.insert(key.to_owned(), value);
            }
            None => {
                server.shift_remove(key);
            }
        }
        true
    })?;
    if found {
        Ok(())
    } else {
        Err(format!(
            "{} does not define MCP server \"{name}\"",
            path.display()
        ))
    }
}

/// Reads an `mcp.json` (empty when missing), lets `edit` change it, and
/// writes it back with its own indentation when `edit` returns true. Other
/// content is kept.
fn edit_servers(
    path: &Path,
    edit: impl FnOnce(&mut Map<String, Value>) -> bool,
) -> Result<(), String> {
    let text = std::fs::read_to_string(path).ok();
    let parsed: Value = match &text {
        Some(text) => serde_json::from_str(text).map_err(|err| err.to_string())?,
        None => Value::Object(Map::new()),
    };
    let Value::Object(mut document) = parsed else {
        return Err(format!(
            "{}: expected an object with an \"mcpServers\" object",
            path.display()
        ));
    };
    if document
        .get("mcpServers")
        .is_some_and(|servers| !servers.is_object())
    {
        return Err(format!(
            "{}: expected an object with an \"mcpServers\" object",
            path.display()
        ));
    }
    if !edit(&mut document) {
        return Ok(());
    }
    // The first indented line's indentation, as pi detects it.
    let indent = text
        .as_deref()
        .and_then(|text| {
            text.lines().find_map(|line| {
                let rest = line.trim_start_matches([' ', '\t']);
                (rest.len() < line.len()
                    && !rest.is_empty()
                    && !rest.starts_with(char::is_whitespace))
                .then(|| &line[..line.len() - rest.len()])
            })
        })
        .unwrap_or("  ");
    let json = yapi_types::json::to_string_pretty(&Value::Object(document), indent)
        .map_err(|err| err.to_string())?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
    }
    yapi_ai::auth::lock::write_atomic(path, format!("{json}\n").as_bytes(), 0o666)
        .map_err(|err| err.to_string())
}

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

    #[test]
    fn validates_like_pi() {
        let stdio = validate_server(
            "fs",
            &json!({"command": "npx", "args": ["-y", "x"], "exposure": "codemode-deferred"}),
        )
        .unwrap();
        assert_eq!(stdio.exposure, Some(McpExposure::Codemode));
        let problems = [
            (
                json!({"command": 1}),
                "server \"x\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)",
            ),
            (
                json!({"url": "ftp://a"}),
                "server \"x\": url must be an http or https URL",
            ),
            (
                json!({"url": "https://a", "type": "sse"}),
                "server \"x\": legacy SSE transport is not supported; use the streamable HTTP URL",
            ),
            (
                json!({"command": "a", "exposure": "all"}),
                "server \"x\": exposure must be one of \"codemode\", \"deferred\", \"direct\", \"hidden\"",
            ),
            (
                json!({"command": "a", "timeout": 0}),
                "server \"x\": timeout must be a positive number of seconds",
            ),
            (
                json!({"url": "http://example.com", "auth": {"provider": "github"}}),
                "server \"x\": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]",
            ),
            (
                json!({"url": "https://a", "oauth": {"callbackUrl": "http://localhost:1/cb", "callbackPort": 2}}),
                "server \"x\": oauth.callbackUrl and oauth.callbackPort name different ports",
            ),
        ];
        for (raw, message) in problems {
            assert_eq!(validate_server("x", &raw).unwrap_err(), message);
        }
        assert_eq!(
            validate_server("a b", &json!({})).unwrap_err(),
            "invalid server name \"a b\" (use letters, digits, \"_\" and \"-\")"
        );
        assert!(
            validate_server(
                "x",
                &json!({"url": "http://[::1]:8080/mcp", "auth": {"provider": "p"}})
            )
            .is_ok()
        );
    }

    #[test]
    fn project_auth_refused() {
        let dir = std::env::temp_dir().join(format!("yapi-mcp-load-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join(PROJECT_DIR).join("mcp.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            r#"{"mcpServers":{"x":{"url":"https://example.invalid/mcp","auth":{"provider":"anthropic"}},"y":{"command":"a"}}}"#,
        )
        .unwrap();
        let agent_dir = dir.join("agent");
        let loaded = load(&agent_dir, &dir, true, None);
        assert_eq!(
            loaded.errors,
            [format!(
                "{}: server \"x\": auth is only allowed in the global mcp.json",
                path.display()
            )]
        );
        let names: Vec<&str> = loaded.servers.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["y"]);
        // An untrusted project's file is not read at all.
        let untrusted = load(&agent_dir, &dir, false, None);
        assert!(untrusted.servers.is_empty() && untrusted.errors.is_empty());

        // A project-only run keeps the global servers its patterns name,
        // auth included, and never looks at the others, so a left-out
        // server neither clashes with a project's nor reports a problem.
        std::fs::create_dir_all(&agent_dir).unwrap();
        std::fs::write(
            agent_dir.join("mcp.json"),
            r#"{"mcpServers":{"github":{"url":"https://example.invalid/mcp","auth":{"provider":"github"}},"slack":{"command":"a"},"my-y":{"command":"a"},"broken":{}}}"#,
        )
        .unwrap();
        std::fs::write(&path, r#"{"mcpServers":{"my_y":{"command":"b"}}}"#).unwrap();
        let keep = ["git*".to_owned()];
        let kept = load(&agent_dir, &dir, true, Some(&keep));
        assert!(kept.errors.is_empty(), "{:?}", kept.errors);
        let names: Vec<&str> = kept.servers.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["github", "my_y"]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn tool_exposure_prefers_exact_names() {
        let config = validate_server(
            "gh",
            &json!({"command": "a", "exposure": "hidden", "toolExposure": {"list_*": "direct", "list_issues": "deferred", "*_pr": "codemode"}}),
        )
        .unwrap();
        assert_eq!(config.tool_exposure("list_issues"), McpExposure::Deferred);
        assert_eq!(config.tool_exposure("list_repos"), McpExposure::Direct);
        assert_eq!(config.tool_exposure("merge_pr"), McpExposure::Codemode);
        assert_eq!(config.tool_exposure("delete"), McpExposure::Hidden);
        assert_eq!(namespace("my-server"), "mcp__my_server");
    }

    #[test]
    fn edits_servers_keeping_indentation() {
        let dir = std::env::temp_dir().join(format!("yapi-mcp-edit-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("mcp.json");
        assert!(!remove_server_config(&path, "x").unwrap());
        assert!(!add_server_config(&path, "a", json!({"command": "a"})).unwrap());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{\n  \"mcpServers\": {\n    \"a\": {\n      \"command\": \"a\"\n    }\n  }\n}\n"
        );
        std::fs::write(
            &path,
            "{\n\t\"other\": 1,\n\t\"mcpServers\": {\"a\": {\"url\": \"https://x\"}}\n}",
        )
        .unwrap();
        assert!(add_server_config(&path, "a", json!({"command": "b"})).unwrap());
        assert!(remove_server_config(&path, "a").unwrap());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{\n\t\"other\": 1,\n\t\"mcpServers\": {}\n}\n"
        );
        assert_eq!(
            update_server_config(&path, "a", ConfigPatch::Enabled(false)).unwrap_err(),
            format!("{} does not define MCP server \"a\"", path.display())
        );
        add_server_config(&path, "a", json!({"command": "a", "enabled": false})).unwrap();
        update_server_config(&path, "a", ConfigPatch::Exposure(McpExposure::Direct)).unwrap();
        update_server_config(&path, "a", ConfigPatch::Enabled(true)).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{\n\t\"other\": 1,\n\t\"mcpServers\": {\n\t\t\"a\": {\n\t\t\t\"command\": \"a\",\n\t\t\t\"exposure\": \"direct\"\n\t\t}\n\t}\n}\n"
        );
        assert_eq!(
            resolve_exposure_aliases(
                &json!({"exposure": "codemode-deferred", "toolExposure": {"t": "codemode-deferred"}})
            ),
            json!({"exposure": "codemode", "toolExposure": {"t": "codemode"}})
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}