Skip to main content

surjection_core/adapters/
detect.rs

1//! Client detection (SPEC 7.7). Advisory and read-only: probes check that
2//! paths exist, look executables up on `PATH` and ask a [`RegistryProbe`];
3//! nothing is ever written.
4
5use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7
8use crate::adapters::location::Location;
9use crate::adapters::spec::AdapterSpec;
10use crate::env::{Env, Os};
11use crate::error::{CoreError, ErrorCode};
12use crate::formats::NativeValue;
13use crate::fs::Fs;
14
15/// One way a client can be found.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Probe {
18    /// A config file or directory exists. A [`Location::Glob`] matches when
19    /// any path matches.
20    Path(Location),
21    /// An executable with this name (no extension) is on `PATH`. On
22    /// Windows each `PATHEXT` extension is tried.
23    Executable(&'static str),
24    /// Windows: an uninstall registry entry with this `DisplayName`.
25    UninstallEntry(&'static str),
26    /// Windows: an MSIX package directory exists (a [`Location::Glob`]
27    /// under `%LOCALAPPDATA%\Packages`).
28    MsixPackage(Location),
29}
30
31/// Read-only access to the Windows registry. The core never opens the
32/// registry itself; the caller passes a real probe on Windows and tests pass
33/// a fake.
34pub trait RegistryProbe {
35    /// Whether an uninstall entry (`HKCU` or `HKLM`, 64- and 32-bit views,
36    /// `Software\Microsoft\Windows\CurrentVersion\Uninstall\*`) has this
37    /// `DisplayName`.
38    fn has_uninstall_entry(&self, display_name: &str) -> bool;
39}
40
41/// A registry with nothing in it (non-Windows hosts, or no registry access).
42#[derive(Debug, Clone, Copy, Default)]
43pub struct NoRegistry;
44
45impl RegistryProbe for NoRegistry {
46    fn has_uninstall_entry(&self, _display_name: &str) -> bool {
47        false
48    }
49}
50
51/// What a probe found.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Evidence {
54    Path(PathBuf),
55    Executable(PathBuf),
56    UninstallEntry(&'static str),
57    MsixPackage(PathBuf),
58}
59
60/// The result of probing one client.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Detection {
63    pub client: &'static str,
64    /// Whether the client has a target on this OS (Claude Desktop has none
65    /// on Linux). Probes do not run when it has none.
66    pub supported: bool,
67    /// Every probe hit, in probe order.
68    pub evidence: Vec<Evidence>,
69    /// Findings about the installation, such as
70    /// `client_mcp_replaced_by_extension`.
71    pub warnings: Vec<CoreError>,
72}
73
74impl Detection {
75    pub fn detected(&self) -> bool {
76        self.supported && !self.evidence.is_empty()
77    }
78}
79
80/// Runs every probe of `spec`, then checks for an extension replacing its
81/// MCP support (user-level installs only; see [`replacing_extension`]).
82pub fn detect(
83    spec: &AdapterSpec,
84    env: &Env,
85    fs: &dyn Fs,
86    registry: &dyn RegistryProbe,
87) -> Detection {
88    let supported = spec
89        .mcp
90        .as_ref()
91        .is_none_or(|mcp| mcp.oses.contains(&env.os()));
92    let mut evidence = Vec::new();
93    let mut warnings = Vec::new();
94    if supported {
95        for probe in spec.detect {
96            run(probe, env, fs, registry, &mut evidence);
97        }
98        warnings.extend(replacing_extension(spec, env, fs, None));
99    }
100    Detection {
101        client: spec.id,
102        supported,
103        evidence,
104        warnings,
105    }
106}
107
108/// An extension that, once installed, replaces a client's own MCP support
109/// (Pi with `pi-mcp-adapter`): the client then no longer loads its MCP file
110/// itself.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct McpExtension {
113    /// Package name (`pi-mcp-adapter`).
114    pub package: &'static str,
115    /// Paths whose existence means the extension is installed (an
116    /// auto-discovered extension dir). [`Location::Project`] entries are
117    /// checked only when a project is given.
118    pub paths: &'static [Location],
119    /// JSON settings files whose top-level `packages` list may name the
120    /// package, as a source string (`npm:pi-mcp-adapter@1.2.0`,
121    /// `git:github.com/example/pi-mcp-adapter`) or an object with such a
122    /// `source`.
123    pub package_lists: &'static [Location],
124}
125
126/// `client_mcp_replaced_by_extension` when an extension that takes over
127/// `spec`'s MCP support is installed for the user or, with `project`, for
128/// that project. Read-only: checks paths and reads the settings files named
129/// by the extension; an unreadable or malformed settings file counts as not
130/// naming it.
131pub fn replacing_extension(
132    spec: &AdapterSpec,
133    env: &Env,
134    fs: &dyn Fs,
135    project: Option<&Path>,
136) -> Option<CoreError> {
137    let mcp = spec.mcp.as_ref()?;
138    mcp.replaced_by.iter().find_map(|extension| {
139        let found = extension
140            .paths
141            .iter()
142            .filter_map(|location| location.resolve(env, project))
143            .find(|path| fs.exists(path))
144            .or_else(|| {
145                extension
146                    .package_lists
147                    .iter()
148                    .filter_map(|location| location.resolve(env, project))
149                    .find(|file| lists_package(fs, file, extension.package))
150            })?;
151        Some(
152            CoreError::new(
153                ErrorCode::ClientMcpReplacedByExtension,
154                format!(
155                    "{} is installed and replaces the MCP support of {}; it may not load the servers Surjection writes",
156                    extension.package, spec.display_name
157                ),
158            )
159            .with_path(found),
160        )
161    })
162}
163
164/// Whether the JSON settings `file` has a `packages` entry for `package`.
165fn lists_package(fs: &dyn Fs, file: &Path, package: &str) -> bool {
166    let Ok(text) = fs.read_to_string(file) else {
167        return false;
168    };
169    let Ok(settings) = NativeValue::parse_json(&text) else {
170        return false;
171    };
172    let Some(packages) = settings
173        .as_object()
174        .and_then(|settings| settings.get("packages"))
175        .and_then(NativeValue::as_array)
176    else {
177        return false;
178    };
179    packages.iter().any(|entry| {
180        let source = match entry {
181            NativeValue::String(source) => Some(source.as_str()),
182            NativeValue::Object(entry) => entry.get("source").and_then(NativeValue::as_str),
183            _ => None,
184        };
185        source.is_some_and(|source| package_name(source) == package)
186    })
187}
188
189/// The package name in a package source: the last path segment without a
190/// `npm:`/`git:` prefix, version or ref suffix (`@1.2.0`, `@v1`) or `.git`.
191fn package_name(source: &str) -> &str {
192    let source = source
193        .strip_prefix("npm:")
194        .or_else(|| source.strip_prefix("git:"))
195        .unwrap_or(source);
196    let last = source
197        .trim_end_matches(['/', '\\'])
198        .rsplit(['/', '\\'])
199        .next()
200        .unwrap_or(source);
201    // `@` past the first character starts a version (`name@1.2.0`); a
202    // leading `@` is an npm scope with no slash left after it.
203    let last = match last.get(1..).and_then(|rest| rest.find('@')) {
204        Some(at) => &last[..at + 1],
205        None => last,
206    };
207    last.strip_suffix(".git").unwrap_or(last)
208}
209
210fn run(
211    probe: &Probe,
212    env: &Env,
213    fs: &dyn Fs,
214    registry: &dyn RegistryProbe,
215    evidence: &mut Vec<Evidence>,
216) {
217    match *probe {
218        Probe::Path(location) => {
219            evidence.extend(
220                location
221                    .expand(env, fs, None)
222                    .into_iter()
223                    .map(Evidence::Path),
224            );
225        }
226        Probe::Executable(name) => {
227            evidence.extend(find_executable(env, fs, name).map(Evidence::Executable));
228        }
229        Probe::UninstallEntry(display_name) => {
230            if env.os() == Os::Windows && registry.has_uninstall_entry(display_name) {
231                evidence.push(Evidence::UninstallEntry(display_name));
232            }
233        }
234        Probe::MsixPackage(location) => {
235            if env.os() == Os::Windows {
236                evidence.extend(
237                    location
238                        .expand(env, fs, None)
239                        .into_iter()
240                        .filter(|path| fs.is_dir(path))
241                        .map(Evidence::MsixPackage),
242                );
243            }
244        }
245    }
246}
247
248/// The first `PATH` entry holding `name` (on Windows `name` plus a
249/// `PATHEXT` extension). Relative `PATH` entries are skipped.
250pub(crate) fn find_executable(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
251    let path = env.var("PATH")?.to_str()?;
252    let windows = env.os() == Os::Windows;
253    let separator = if windows { ';' } else { ':' };
254    let extensions: Vec<String> = if windows {
255        env.var("PATHEXT")
256            .and_then(OsStr::to_str)
257            .unwrap_or(".COM;.EXE;.BAT;.CMD")
258            .split(';')
259            .filter(|ext| !ext.is_empty())
260            .map(str::to_ascii_lowercase)
261            .collect()
262    } else {
263        vec![String::new()]
264    };
265    path.split(separator)
266        .map(|dir| Path::new(dir.trim_matches('"')))
267        .filter(|dir| dir.is_absolute())
268        .flat_map(|dir| {
269            extensions
270                .iter()
271                .map(move |ext| dir.join(format!("{name}{ext}")))
272        })
273        .find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
274}