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}
88
89#[derive(Debug, Clone, Copy)]
91pub struct Profiles {
92 pub default: &'static str,
95 pub dir: Location,
97 pub rel: &'static str,
99 pub valid_name: fn(&str) -> bool,
101}
102
103pub type UserFiles =
107 fn(&Env, &dyn Fs, &ClientPrefs) -> Result<Vec<(PathBuf, Option<String>)>, CoreError>;
108
109pub fn exact_names(a: &str, b: &str) -> bool {
111 a == b
112}
113
114#[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 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#[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 pub project: Option<PathBuf>,
159 pub profile: Option<String>,
162 pub skeleton: &'static str,
164 pub warnings: Vec<CoreError>,
166}
167
168impl Target {
169 pub fn container_keys(&self) -> Result<Vec<String>, CoreError> {
171 self.container.keys(self.os, self.project.as_deref())
172 }
173
174 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 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 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(©);
288 targets.push(target(copy, None, vec![warning]));
289 }
290 }
291 }
292 Ok(targets)
293 }
294
295 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 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 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
430fn 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}