Skip to main content

surjection_core/adapters/
spec.rs

1//! The declarative adapter table entry (SPEC 7.1 `AdapterSpec`, `McpSpec`)
2//! and the target files it resolves to.
3
4use std::path::{Path, PathBuf};
5
6use crate::adapters::caps::{Caps, ProjectDisable};
7use crate::adapters::detect::{McpExtension, Probe};
8use crate::adapters::location::{Location, project_key};
9use crate::adapters::mapper::{EntryMapper, MapError, RenderedServer, WriteCx};
10use crate::env::{Env, Os};
11use crate::error::{CoreError, ErrorCode};
12use crate::formats::{Document, Format, NativeMap, NativeValue};
13use crate::fs::Fs;
14use crate::model::applied::Scope;
15use crate::model::clients::ClientPrefs;
16
17/// Support tier (SPEC 20.2).
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum Tier {
20    /// Daily clients, first wave.
21    A,
22    /// Daily clients, second wave.
23    B,
24    /// Supported.
25    C,
26    /// Best effort or ported.
27    D,
28}
29
30/// One client: identity, detection probes and MCP targets.
31pub struct AdapterSpec {
32    /// Client id (`claude-code`), as used in store files.
33    pub id: &'static str,
34    pub display_name: &'static str,
35    pub tier: Tier,
36    /// Detection probes; any hit detects the client (SPEC 7.7).
37    pub detect: &'static [Probe],
38    pub mcp: Option<McpSpec>,
39}
40
41/// Where and how a client keeps MCP servers.
42pub struct McpSpec {
43    /// Operating systems the client has MCP targets on.
44    pub oses: &'static [Os],
45    /// Surjection only reads this client's files (import, effective view) and
46    /// never writes them (`vscode-legacy`): it is never selected for a
47    /// write, and naming it in an enable list reports `read_only_client`.
48    pub read_only: bool,
49    /// User-scope candidates: the first existing one wins, else `[0]` is
50    /// created. With [`McpSpec::profiles`], this is the default profile.
51    pub user: &'static [Location],
52    /// Computes the user files instead of [`McpSpec::user`] when set (VS
53    /// Code variants and profiles selected in `clients.toml`). The first
54    /// file stands for the client in the effective view.
55    pub user_files: Option<UserFiles>,
56    /// Extra copies of the user file, each written too when it exists (the
57    /// Claude Desktop MSIX copy). Usually [`Location::Glob`].
58    pub user_mirrors: &'static [Location],
59    /// Named profiles, each with its own user file (omp), selected by
60    /// `profiles` in `clients.toml`.
61    pub profiles: Option<Profiles>,
62    /// Shared project candidates, relative to `<P>`.
63    pub project: &'static [Location],
64    /// Private project candidates; may point into a user file whose
65    /// container holds a [`ContainerPath::PROJECT_KEY`] segment.
66    pub project_local: &'static [Location],
67    pub format: Format,
68    /// The text of a new file (omp's `$schema` line); empty for most
69    /// clients.
70    pub skeleton: &'static str,
71    /// Server container in user and project files.
72    pub container: ContainerPath,
73    /// Server container in the project-local file.
74    pub project_local_container: ContainerPath,
75    /// Containers in the same files that the client still loads but Surjection
76    /// only reads (import, effective view) and never edits (Codex legacy
77    /// `[mcp.servers]`).
78    pub legacy_containers: &'static [ContainerPath],
79    /// Whether the client treats two entry names as the same server (Pi:
80    /// `-` and `_` are equal). Most clients compare exactly
81    /// ([`exact_names`]).
82    pub same_name: fn(&str, &str) -> bool,
83    /// Extensions that replace the client's MCP support when installed.
84    pub replaced_by: &'static [McpExtension],
85    pub mapper: &'static dyn EntryMapper,
86    pub caps: Caps,
87}
88
89/// Named profiles of a client (omp `~/.omp/profiles/<name>/agent/mcp.json`).
90#[derive(Debug, Clone, Copy)]
91pub struct Profiles {
92    /// The name that selects [`McpSpec::user`] (`default`). It is also the
93    /// selection when `clients.toml` has no `profiles` key.
94    pub default: &'static str,
95    /// The directory holding one directory per named profile.
96    pub dir: Location,
97    /// The user file inside a profile's directory, `/`-separated.
98    pub rel: &'static str,
99    /// Whether a profile name is valid for the client.
100    pub valid_name: fn(&str) -> bool,
101}
102
103/// [`McpSpec::user_files`]: the user files `prefs` selects, in order and
104/// without duplicates, each with a label for [`Target::profile`] (`None`
105/// for the default file). Only lists directories; never reads files.
106pub type UserFiles =
107    fn(&Env, &dyn Fs, &ClientPrefs) -> Result<Vec<(PathBuf, Option<String>)>, CoreError>;
108
109/// [`McpSpec::same_name`] for clients that compare names exactly.
110pub fn exact_names(a: &str, b: &str) -> bool {
111    a == b
112}
113
114/// A path of keys from the document root to a container or list. A
115/// [`ContainerPath::PROJECT_KEY`] segment stands for the key of the project
116/// in a map keyed by project path (see [`project_key`]).
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct ContainerPath(pub &'static [&'static str]);
119
120impl ContainerPath {
121    pub const PROJECT_KEY: &'static str = "{project_key}";
122
123    pub const fn segments(self) -> &'static [&'static str] {
124        self.0
125    }
126
127    /// The keys of this path. A project key segment is the key Claude Code
128    /// uses for `project` (see [`project_key`]).
129    pub fn keys(self, os: Os, project: Option<&Path>) -> Result<Vec<String>, CoreError> {
130        let mut keys: Vec<String> = Vec::with_capacity(self.0.len());
131        for segment in self.0 {
132            if *segment != Self::PROJECT_KEY {
133                keys.push((*segment).to_owned());
134                continue;
135            }
136            let project = project.ok_or_else(|| {
137                CoreError::new(
138                    ErrorCode::InvalidPath,
139                    "this container is keyed by project and needs a project folder",
140                )
141            })?;
142            keys.push(project_key(os, project));
143        }
144        Ok(keys)
145    }
146}
147
148/// One native file to write for a client in a scope.
149#[derive(Debug, Clone, PartialEq)]
150pub struct Target {
151    pub client: &'static str,
152    pub scope: Scope,
153    pub os: Os,
154    pub file: PathBuf,
155    pub format: Format,
156    pub container: ContainerPath,
157    /// The project folder, for project scopes.
158    pub project: Option<PathBuf>,
159    /// The named profile this user file belongs to (omp); `None` for the
160    /// default profile and for clients without profiles.
161    pub profile: Option<String>,
162    /// The text of the file when it does not exist yet.
163    pub skeleton: &'static str,
164    /// Warnings attached to this target (for example `msix_dual_write`).
165    pub warnings: Vec<CoreError>,
166}
167
168impl Target {
169    /// The keys of the container entries go in.
170    pub fn container_keys(&self) -> Result<Vec<String>, CoreError> {
171        self.container.keys(self.os, self.project.as_deref())
172    }
173
174    /// The document to edit when [`Target::file`] does not exist: the
175    /// client's skeleton (empty for most clients).
176    pub fn new_document(&self) -> Document {
177        Document::parse(self.skeleton.as_bytes(), self.format)
178            .expect("an adapter skeleton parses in its format")
179    }
180}
181
182impl McpSpec {
183    /// The project entry that hides a same-named user server `server` when
184    /// the client suppresses through `enabled: false`
185    /// ([`ProjectDisable::EnabledFalse`]): `{ "enabled": false }` alone for
186    /// a partial override, else `server` itself with `enabled: false`.
187    /// `None` when the client suppresses some other way, or not at all.
188    pub fn suppression_entry(
189        &self,
190        server: &RenderedServer,
191        os: Os,
192    ) -> Result<Option<NativeValue>, MapError> {
193        match self.caps.project_disable {
194            Some(ProjectDisable::EnabledFalse { partial: true }) => {
195                let mut entry = NativeMap::new();
196                entry.insert("enabled", NativeValue::Bool(false));
197                Ok(Some(NativeValue::Object(entry)))
198            }
199            Some(ProjectDisable::EnabledFalse { partial: false }) => {
200                let disabled = RenderedServer {
201                    enabled: false,
202                    ..server.clone()
203                };
204                self.mapper
205                    .to_native(&disabled, &WriteCx { os, existing: None })
206                    .map(Some)
207            }
208            Some(ProjectDisable::ListMember(_)) | None => Ok(None),
209        }
210    }
211}
212
213impl AdapterSpec {
214    /// The files this client's MCP servers go to in `scope`. Only checks
215    /// which files exist; never reads or writes them. `prefs` is the
216    /// client's table in `clients.toml`; it selects the profiles of a
217    /// client with [`McpSpec::profiles`] (an empty list selects none) and
218    /// the files of one with [`McpSpec::user_files`], and is ignored by the
219    /// others.
220    ///
221    /// Errors: `not_supported_on_os` when the client has no MCP target on
222    /// this OS, `scope_not_supported` when it has none in `scope`,
223    /// `invalid_path` for a project scope without an absolute `project`,
224    /// `invalid_value` for a profile name the client rejects.
225    pub fn mcp_targets(
226        &self,
227        env: &Env,
228        fs: &dyn Fs,
229        scope: Scope,
230        project: Option<&Path>,
231        prefs: &ClientPrefs,
232    ) -> Result<Vec<Target>, CoreError> {
233        let mcp = self.mcp_on(env.os())?;
234        let (candidates, container) = match scope {
235            Scope::User => (mcp.user, mcp.container),
236            Scope::Project => (mcp.project, mcp.container),
237            Scope::ProjectLocal => (mcp.project_local, mcp.project_local_container),
238        };
239        let project = match scope {
240            Scope::User => None,
241            Scope::Project | Scope::ProjectLocal => Some(project_folder(project)?),
242        };
243        if candidates.is_empty() {
244            return Err(CoreError::new(
245                ErrorCode::ScopeNotSupported,
246                format!(
247                    "{} has no {} MCP config",
248                    self.display_name,
249                    scope_name(scope)
250                ),
251            ));
252        }
253        let target = |file: PathBuf, profile: Option<String>, warnings: Vec<CoreError>| Target {
254            client: self.id,
255            scope,
256            os: env.os(),
257            file,
258            format: mcp.format,
259            container,
260            project: project.map(Path::to_path_buf),
261            profile,
262            skeleton: mcp.skeleton,
263            warnings,
264        };
265        let files = match (scope, &mcp.profiles, mcp.user_files) {
266            (Scope::User, _, Some(user_files)) => user_files(env, fs, prefs)?,
267            (Scope::User, Some(profiles), None) => self.profile_files(profiles, env, fs, prefs)?,
268            _ => vec![(first_existing(self, candidates, env, fs, project)?, None)],
269        };
270        let mut targets = Vec::with_capacity(files.len());
271        for (file, profile) in files {
272            targets.push(target(file, profile, Vec::new()));
273        }
274        if scope == Scope::User
275            && let Some(file) = targets.first().map(|target| target.file.clone())
276        {
277            for mirror in mcp.user_mirrors {
278                for copy in mirror.expand(env, fs, None) {
279                    let warning = CoreError::new(
280                        ErrorCode::MsixDualWrite,
281                        format!(
282                            "{} keeps a packaged (MSIX) copy of its config; both {} and this copy are written",
283                            self.display_name,
284                            file.display()
285                        ),
286                    )
287                    .with_path(&copy);
288                    targets.push(target(copy, None, vec![warning]));
289                }
290            }
291        }
292        Ok(targets)
293    }
294
295    /// Where a project hides a same-named user server, as a target:
296    ///
297    /// - [`ProjectDisable::ListMember`]: the project-local file (the
298    ///   project file for a client without one, Gemini `mcp.excluded`),
299    ///   with the list as its container (Claude Code
300    ///   `projects["<P>"].disabledMcpServers`), for
301    ///   [`Document::set_list_member`].
302    /// - [`ProjectDisable::EnabledFalse`]: the project file and its server
303    ///   container, for an upsert of [`McpSpec::suppression_entry`].
304    ///
305    /// `None` when the client cannot suppress a user server in a project.
306    pub fn suppression_target(
307        &self,
308        env: &Env,
309        fs: &dyn Fs,
310        project: &Path,
311        prefs: &ClientPrefs,
312    ) -> Result<Option<Target>, CoreError> {
313        let mcp = self.mcp_on(env.os())?;
314        let (scope, list) = match mcp.caps.project_disable {
315            Some(ProjectDisable::ListMember(list)) if mcp.project_local.is_empty() => {
316                (Scope::Project, Some(list))
317            }
318            Some(ProjectDisable::ListMember(list)) => (Scope::ProjectLocal, Some(list)),
319            Some(ProjectDisable::EnabledFalse { .. }) => (Scope::Project, None),
320            None => return Ok(None),
321        };
322        let mut targets = self.mcp_targets(env, fs, scope, Some(project), prefs)?;
323        let mut target = targets.swap_remove(0);
324        if let Some(list) = list {
325            target.container = list;
326        }
327        Ok(Some(target))
328    }
329
330    /// `collision` for each key in `keys` that the client treats as the
331    /// same server as `name` without being equal to it (Pi `my-tool` and
332    /// `my_tool`). `keys` are the names already in the container, or other
333    /// names desired for the same target.
334    pub fn name_collisions(&self, name: &str, keys: &[String]) -> Vec<CoreError> {
335        let Some(mcp) = &self.mcp else {
336            return Vec::new();
337        };
338        keys.iter()
339            .filter(|key| key.as_str() != name && (mcp.same_name)(key, name))
340            .map(|key| {
341                CoreError::new(
342                    ErrorCode::Collision,
343                    format!(
344                        "{} treats {key:?} and {name:?} as the same server; set `native_name` or remove one",
345                        self.display_name
346                    ),
347                )
348            })
349            .collect()
350    }
351
352    /// The user files of the profiles `prefs` selects, in order, without
353    /// duplicates.
354    fn profile_files(
355        &self,
356        profiles: &Profiles,
357        env: &Env,
358        fs: &dyn Fs,
359        prefs: &ClientPrefs,
360    ) -> Result<Vec<(PathBuf, Option<String>)>, CoreError> {
361        let mcp = self.mcp_on(env.os())?;
362        let default = [profiles.default.to_owned()];
363        let names = prefs.profiles.as_deref().unwrap_or(&default);
364        let mut files: Vec<(PathBuf, Option<String>)> = Vec::with_capacity(names.len());
365        for name in names {
366            let entry = if name == profiles.default {
367                (first_existing(self, mcp.user, env, fs, None)?, None)
368            } else {
369                if !(profiles.valid_name)(name) {
370                    return Err(CoreError::new(
371                        ErrorCode::InvalidValue,
372                        format!("{name:?} is not a valid {} profile name", self.display_name),
373                    ));
374                }
375                let dir = profiles.dir.resolve(env, None).ok_or_else(|| {
376                    CoreError::new(
377                        ErrorCode::NotSupportedOnOs,
378                        format!(
379                            "{} has no profile directory on {}",
380                            self.display_name,
381                            env.os().as_str()
382                        ),
383                    )
384                })?;
385                let mut file = dir.join(name);
386                for part in profiles.rel.split('/').filter(|part| !part.is_empty()) {
387                    file.push(part);
388                }
389                (file, Some(name.clone()))
390            };
391            if !files.iter().any(|(file, _)| *file == entry.0) {
392                files.push(entry);
393            }
394        }
395        Ok(files)
396    }
397
398    fn mcp_on(&self, os: Os) -> Result<&McpSpec, CoreError> {
399        let mcp = self.mcp.as_ref().ok_or_else(|| {
400            CoreError::new(
401                ErrorCode::ScopeNotSupported,
402                format!("{} has no MCP config", self.display_name),
403            )
404        })?;
405        if !mcp.oses.contains(&os) {
406            return Err(CoreError::new(
407                ErrorCode::NotSupportedOnOs,
408                format!("{} has no MCP config on {}", self.display_name, os.as_str()),
409            ));
410        }
411        Ok(mcp)
412    }
413}
414
415fn project_folder(project: Option<&Path>) -> Result<&Path, CoreError> {
416    match project {
417        Some(path) if path.is_absolute() => Ok(path),
418        Some(path) => Err(CoreError::new(
419            ErrorCode::InvalidPath,
420            "the project folder must be an absolute path",
421        )
422        .with_path(path)),
423        None => Err(CoreError::new(
424            ErrorCode::InvalidPath,
425            "a project scope needs a project folder",
426        )),
427    }
428}
429
430/// The first candidate that exists, else the first one that resolves.
431fn first_existing(
432    spec: &AdapterSpec,
433    candidates: &[Location],
434    env: &Env,
435    fs: &dyn Fs,
436    project: Option<&Path>,
437) -> Result<PathBuf, CoreError> {
438    let resolved: Vec<PathBuf> = candidates
439        .iter()
440        .filter_map(|location| location.resolve(env, project))
441        .collect();
442    resolved
443        .iter()
444        .find(|path| fs.exists(path))
445        .or_else(|| resolved.first())
446        .cloned()
447        .ok_or_else(|| {
448            CoreError::new(
449                ErrorCode::NotSupportedOnOs,
450                format!(
451                    "{} has no MCP config path on {}",
452                    spec.display_name,
453                    env.os().as_str()
454                ),
455            )
456        })
457}
458
459fn scope_name(scope: Scope) -> &'static str {
460    match scope {
461        Scope::User => "user",
462        Scope::Project => "project",
463        Scope::ProjectLocal => "project-local",
464    }
465}