1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum Tier {
20 A,
22 B,
24 C,
26 D,
28}
29
30pub struct AdapterSpec {
32 pub id: &'static str,
34 pub display_name: &'static str,
35 pub tier: Tier,
36 pub detect: &'static [Probe],
38 pub mcp: Option<McpSpec>,
39}
40
41pub struct McpSpec {
43 pub oses: &'static [Os],
45 pub read_only: bool,
49 pub user: &'static [Location],
52 pub user_files: Option<UserFiles>,
56 pub user_mirrors: &'static [Location],
59 pub profiles: Option<Profiles>,
62 pub project: &'static [Location],
64 pub project_local: &'static [Location],
67 pub format: Format,
68 pub skeleton: &'static str,
71 pub container: ContainerPath,
73 pub project_local_container: ContainerPath,
75 pub legacy_containers: &'static [ContainerPath],
79 pub same_name: fn(&str, &str) -> bool,
83 pub replaced_by: &'static [McpExtension],
85 pub mapper: &'static dyn EntryMapper,
86 pub caps: Caps,
87 pub sign_in: crate::adapters::sign_in::SignIn,
89}
90
91#[derive(Debug, Clone, Copy)]
93pub struct Profiles {
94 pub default: &'static str,
97 pub dir: Location,
99 pub rel: &'static str,
101 pub valid_name: fn(&str) -> bool,
103}
104
105pub type UserFiles =
109 fn(&Env, &dyn Fs, &ClientPrefs) -> Result<Vec<(PathBuf, Option<String>)>, CoreError>;
110
111pub fn exact_names(a: &str, b: &str) -> bool {
113 a == b
114}
115
116#[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 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#[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 pub project: Option<PathBuf>,
161 pub profile: Option<String>,
164 pub skeleton: &'static str,
166 pub warnings: Vec<CoreError>,
168}
169
170impl Target {
171 pub fn container_keys(&self) -> Result<Vec<String>, CoreError> {
173 self.container.keys(self.os, self.project.as_deref())
174 }
175
176 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 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 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(©);
290 targets.push(target(copy, None, vec![warning]));
291 }
292 }
293 }
294 Ok(targets)
295 }
296
297 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 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 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
432fn 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}