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    /// How the client signs in to a remote server that uses OAuth (#47).
88    pub sign_in: crate::adapters::sign_in::SignIn,
89}
90
91/// Named profiles of a client (omp `~/.omp/profiles/<name>/agent/mcp.json`).
92#[derive(Debug, Clone, Copy)]
93pub struct Profiles {
94    /// The name that selects [`McpSpec::user`] (`default`). It is also the
95    /// selection when `clients.toml` has no `profiles` key.
96    pub default: &'static str,
97    /// The directory holding one directory per named profile.
98    pub dir: Location,
99    /// The user file inside a profile's directory, `/`-separated.
100    pub rel: &'static str,
101    /// Whether a profile name is valid for the client.
102    pub valid_name: fn(&str) -> bool,
103}
104
105/// [`McpSpec::user_files`]: the user files `prefs` selects, in order and
106/// without duplicates, each with a label for [`Target::profile`] (`None`
107/// for the default file). Only lists directories; never reads files.
108pub type UserFiles =
109    fn(&Env, &dyn Fs, &ClientPrefs) -> Result<Vec<(PathBuf, Option<String>)>, CoreError>;
110
111/// [`McpSpec::same_name`] for clients that compare names exactly.
112pub fn exact_names(a: &str, b: &str) -> bool {
113    a == b
114}
115
116/// A path of keys from the document root to a container or list. A
117/// [`ContainerPath::PROJECT_KEY`] segment stands for the key of the project
118/// in a map keyed by project path (see [`project_key`]).
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct ContainerPath(pub &'static [&'static str]);
121
122impl ContainerPath {
123    pub const PROJECT_KEY: &'static str = "{project_key}";
124
125    pub const fn segments(self) -> &'static [&'static str] {
126        self.0
127    }
128
129    /// The keys of this path. A project key segment is the key Claude Code
130    /// uses for `project` (see [`project_key`]).
131    pub fn keys(self, os: Os, project: Option<&Path>) -> Result<Vec<String>, CoreError> {
132        let mut keys: Vec<String> = Vec::with_capacity(self.0.len());
133        for segment in self.0 {
134            if *segment != Self::PROJECT_KEY {
135                keys.push((*segment).to_owned());
136                continue;
137            }
138            let project = project.ok_or_else(|| {
139                CoreError::new(
140                    ErrorCode::InvalidPath,
141                    "this container is keyed by project and needs a project folder",
142                )
143            })?;
144            keys.push(project_key(os, project));
145        }
146        Ok(keys)
147    }
148}
149
150/// One native file to write for a client in a scope.
151#[derive(Debug, Clone, PartialEq)]
152pub struct Target {
153    pub client: &'static str,
154    pub scope: Scope,
155    pub os: Os,
156    pub file: PathBuf,
157    pub format: Format,
158    pub container: ContainerPath,
159    /// The project folder, for project scopes.
160    pub project: Option<PathBuf>,
161    /// The named profile this user file belongs to (omp); `None` for the
162    /// default profile and for clients without profiles.
163    pub profile: Option<String>,
164    /// The text of the file when it does not exist yet.
165    pub skeleton: &'static str,
166    /// Warnings attached to this target (for example `msix_dual_write`).
167    pub warnings: Vec<CoreError>,
168}
169
170impl Target {
171    /// The keys of the container entries go in.
172    pub fn container_keys(&self) -> Result<Vec<String>, CoreError> {
173        self.container.keys(self.os, self.project.as_deref())
174    }
175
176    /// The document to edit when [`Target::file`] does not exist: the
177    /// client's skeleton (empty for most clients).
178    pub fn new_document(&self) -> Document {
179        Document::parse(self.skeleton.as_bytes(), self.format)
180            .expect("an adapter skeleton parses in its format")
181    }
182}
183
184impl McpSpec {
185    /// The project entry that hides a same-named user server `server` when
186    /// the client suppresses through `enabled: false`
187    /// ([`ProjectDisable::EnabledFalse`]): `{ "enabled": false }` alone for
188    /// a partial override, else `server` itself with `enabled: false`.
189    /// `None` when the client suppresses some other way, or not at all.
190    pub fn suppression_entry(
191        &self,
192        server: &RenderedServer,
193        os: Os,
194    ) -> Result<Option<NativeValue>, MapError> {
195        match self.caps.project_disable {
196            Some(ProjectDisable::EnabledFalse { partial: true }) => {
197                let mut entry = NativeMap::new();
198                entry.insert("enabled", NativeValue::Bool(false));
199                Ok(Some(NativeValue::Object(entry)))
200            }
201            Some(ProjectDisable::EnabledFalse { partial: false }) => {
202                let disabled = RenderedServer {
203                    enabled: false,
204                    ..server.clone()
205                };
206                self.mapper
207                    .to_native(&disabled, &WriteCx { os, existing: None })
208                    .map(Some)
209            }
210            Some(ProjectDisable::ListMember(_)) | None => Ok(None),
211        }
212    }
213}
214
215impl AdapterSpec {
216    /// The files this client's MCP servers go to in `scope`. Only checks
217    /// which files exist; never reads or writes them. `prefs` is the
218    /// client's table in `clients.toml`; it selects the profiles of a
219    /// client with [`McpSpec::profiles`] (an empty list selects none) and
220    /// the files of one with [`McpSpec::user_files`], and is ignored by the
221    /// others.
222    ///
223    /// Errors: `not_supported_on_os` when the client has no MCP target on
224    /// this OS, `scope_not_supported` when it has none in `scope`,
225    /// `invalid_path` for a project scope without an absolute `project`,
226    /// `invalid_value` for a profile name the client rejects.
227    pub fn mcp_targets(
228        &self,
229        env: &Env,
230        fs: &dyn Fs,
231        scope: Scope,
232        project: Option<&Path>,
233        prefs: &ClientPrefs,
234    ) -> Result<Vec<Target>, CoreError> {
235        let mcp = self.mcp_on(env.os())?;
236        let (candidates, container) = match scope {
237            Scope::User => (mcp.user, mcp.container),
238            Scope::Project => (mcp.project, mcp.container),
239            Scope::ProjectLocal => (mcp.project_local, mcp.project_local_container),
240        };
241        let project = match scope {
242            Scope::User => None,
243            Scope::Project | Scope::ProjectLocal => Some(project_folder(project)?),
244        };
245        if candidates.is_empty() {
246            return Err(CoreError::new(
247                ErrorCode::ScopeNotSupported,
248                format!(
249                    "{} has no {} MCP config",
250                    self.display_name,
251                    scope_name(scope)
252                ),
253            ));
254        }
255        let target = |file: PathBuf, profile: Option<String>, warnings: Vec<CoreError>| Target {
256            client: self.id,
257            scope,
258            os: env.os(),
259            file,
260            format: mcp.format,
261            container,
262            project: project.map(Path::to_path_buf),
263            profile,
264            skeleton: mcp.skeleton,
265            warnings,
266        };
267        let files = match (scope, &mcp.profiles, mcp.user_files) {
268            (Scope::User, _, Some(user_files)) => user_files(env, fs, prefs)?,
269            (Scope::User, Some(profiles), None) => self.profile_files(profiles, env, fs, prefs)?,
270            _ => vec![(first_existing(self, candidates, env, fs, project)?, None)],
271        };
272        let mut targets = Vec::with_capacity(files.len());
273        for (file, profile) in files {
274            targets.push(target(file, profile, Vec::new()));
275        }
276        if scope == Scope::User
277            && let Some(file) = targets.first().map(|target| target.file.clone())
278        {
279            for mirror in mcp.user_mirrors {
280                for copy in mirror.expand(env, fs, None) {
281                    let warning = CoreError::new(
282                        ErrorCode::MsixDualWrite,
283                        format!(
284                            "{} keeps a packaged (MSIX) copy of its config; both {} and this copy are written",
285                            self.display_name,
286                            file.display()
287                        ),
288                    )
289                    .with_path(&copy);
290                    targets.push(target(copy, None, vec![warning]));
291                }
292            }
293        }
294        Ok(targets)
295    }
296
297    /// Where a project hides a same-named user server, as a target:
298    ///
299    /// - [`ProjectDisable::ListMember`]: the project-local file (the
300    ///   project file for a client without one, Gemini `mcp.excluded`),
301    ///   with the list as its container (Claude Code
302    ///   `projects["<P>"].disabledMcpServers`), for
303    ///   [`Document::set_list_member`].
304    /// - [`ProjectDisable::EnabledFalse`]: the project file and its server
305    ///   container, for an upsert of [`McpSpec::suppression_entry`].
306    ///
307    /// `None` when the client cannot suppress a user server in a project.
308    pub fn suppression_target(
309        &self,
310        env: &Env,
311        fs: &dyn Fs,
312        project: &Path,
313        prefs: &ClientPrefs,
314    ) -> Result<Option<Target>, CoreError> {
315        let mcp = self.mcp_on(env.os())?;
316        let (scope, list) = match mcp.caps.project_disable {
317            Some(ProjectDisable::ListMember(list)) if mcp.project_local.is_empty() => {
318                (Scope::Project, Some(list))
319            }
320            Some(ProjectDisable::ListMember(list)) => (Scope::ProjectLocal, Some(list)),
321            Some(ProjectDisable::EnabledFalse { .. }) => (Scope::Project, None),
322            None => return Ok(None),
323        };
324        let mut targets = self.mcp_targets(env, fs, scope, Some(project), prefs)?;
325        let mut target = targets.swap_remove(0);
326        if let Some(list) = list {
327            target.container = list;
328        }
329        Ok(Some(target))
330    }
331
332    /// `collision` for each key in `keys` that the client treats as the
333    /// same server as `name` without being equal to it (Pi `my-tool` and
334    /// `my_tool`). `keys` are the names already in the container, or other
335    /// names desired for the same target.
336    pub fn name_collisions(&self, name: &str, keys: &[String]) -> Vec<CoreError> {
337        let Some(mcp) = &self.mcp else {
338            return Vec::new();
339        };
340        keys.iter()
341            .filter(|key| key.as_str() != name && (mcp.same_name)(key, name))
342            .map(|key| {
343                CoreError::new(
344                    ErrorCode::Collision,
345                    format!(
346                        "{} treats {key:?} and {name:?} as the same server; set `native_name` or remove one",
347                        self.display_name
348                    ),
349                )
350            })
351            .collect()
352    }
353
354    /// The user files of the profiles `prefs` selects, in order, without
355    /// duplicates.
356    fn profile_files(
357        &self,
358        profiles: &Profiles,
359        env: &Env,
360        fs: &dyn Fs,
361        prefs: &ClientPrefs,
362    ) -> Result<Vec<(PathBuf, Option<String>)>, CoreError> {
363        let mcp = self.mcp_on(env.os())?;
364        let default = [profiles.default.to_owned()];
365        let names = prefs.profiles.as_deref().unwrap_or(&default);
366        let mut files: Vec<(PathBuf, Option<String>)> = Vec::with_capacity(names.len());
367        for name in names {
368            let entry = if name == profiles.default {
369                (first_existing(self, mcp.user, env, fs, None)?, None)
370            } else {
371                if !(profiles.valid_name)(name) {
372                    return Err(CoreError::new(
373                        ErrorCode::InvalidValue,
374                        format!("{name:?} is not a valid {} profile name", self.display_name),
375                    ));
376                }
377                let dir = profiles.dir.resolve(env, None).ok_or_else(|| {
378                    CoreError::new(
379                        ErrorCode::NotSupportedOnOs,
380                        format!(
381                            "{} has no profile directory on {}",
382                            self.display_name,
383                            env.os().as_str()
384                        ),
385                    )
386                })?;
387                let mut file = dir.join(name);
388                for part in profiles.rel.split('/').filter(|part| !part.is_empty()) {
389                    file.push(part);
390                }
391                (file, Some(name.clone()))
392            };
393            if !files.iter().any(|(file, _)| *file == entry.0) {
394                files.push(entry);
395            }
396        }
397        Ok(files)
398    }
399
400    fn mcp_on(&self, os: Os) -> Result<&McpSpec, CoreError> {
401        let mcp = self.mcp.as_ref().ok_or_else(|| {
402            CoreError::new(
403                ErrorCode::ScopeNotSupported,
404                format!("{} has no MCP config", self.display_name),
405            )
406        })?;
407        if !mcp.oses.contains(&os) {
408            return Err(CoreError::new(
409                ErrorCode::NotSupportedOnOs,
410                format!("{} has no MCP config on {}", self.display_name, os.as_str()),
411            ));
412        }
413        Ok(mcp)
414    }
415}
416
417fn project_folder(project: Option<&Path>) -> Result<&Path, CoreError> {
418    match project {
419        Some(path) if path.is_absolute() => Ok(path),
420        Some(path) => Err(CoreError::new(
421            ErrorCode::InvalidPath,
422            "the project folder must be an absolute path",
423        )
424        .with_path(path)),
425        None => Err(CoreError::new(
426            ErrorCode::InvalidPath,
427            "a project scope needs a project folder",
428        )),
429    }
430}
431
432/// The first candidate that exists, else the first one that resolves.
433fn first_existing(
434    spec: &AdapterSpec,
435    candidates: &[Location],
436    env: &Env,
437    fs: &dyn Fs,
438    project: Option<&Path>,
439) -> Result<PathBuf, CoreError> {
440    let resolved: Vec<PathBuf> = candidates
441        .iter()
442        .filter_map(|location| location.resolve(env, project))
443        .collect();
444    resolved
445        .iter()
446        .find(|path| fs.exists(path))
447        .or_else(|| resolved.first())
448        .cloned()
449        .ok_or_else(|| {
450            CoreError::new(
451                ErrorCode::NotSupportedOnOs,
452                format!(
453                    "{} has no MCP config path on {}",
454                    spec.display_name,
455                    env.os().as_str()
456                ),
457            )
458        })
459}
460
461fn scope_name(scope: Scope) -> &'static str {
462    match scope {
463        Scope::User => "user",
464        Scope::Project => "project",
465        Scope::ProjectLocal => "project-local",
466    }
467}