mur-common 2.91.0

Shared types and traits for the MUR ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Shared executable-path resolution.
//!
//! A single source of truth for turning a command (bare program name or path)
//! into the absolute, symlink-resolved binary that will actually be executed.
//! Used by both install-time MCP pinning (`mur agent mcp pin`) and the runtime
//! startup verification (B0 rules 6 & 11) so a bare `command` like `node`
//! resolves identically across the two passes — otherwise the runtime hashes a
//! CWD-relative path that doesn't exist and silently skips the pin/signature
//! check while `Command::new` runs the PATH-resolved binary.

use anyhow::{Context, Result, bail};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};

/// File name of the MUR MCP server binary.
#[cfg(windows)]
const MCP_SERVER_BIN: &str = "mur-mcp-server.exe";
#[cfg(not(windows))]
const MCP_SERVER_BIN: &str = "mur-mcp-server";

/// Canonical location MUR keeps its own copy of the MCP server binary:
/// `~/.mur/mcp-servers/mur-mcp-server` (honors `$MUR_HOME`). Stable across how
/// `mur` itself was installed (brew / cargo / source) and across upgrades, so
/// agent profiles can pin this path once and never go stale.
pub fn bundled_mcp_server_path() -> PathBuf {
    crate::trust::mur_home()
        .join("mcp-servers")
        .join(MCP_SERVER_BIN)
}

/// Ensure [`bundled_mcp_server_path`] exists and matches the `mur-mcp-server`
/// shipped alongside the running `mur` binary, copying it into place when
/// missing or out of date. Returns the canonical target path.
///
/// Source resolution: the sibling of the current executable first (brew, cargo
/// and source builds all colocate the two binaries), then `mur-mcp-server` on
/// `PATH`. If no source is found but a copy already exists, that copy is
/// returned (usable, just can't self-update). Errors only when there is neither
/// a source nor an existing copy.
///
/// Call this BEFORE the kernel sandbox seals — the copy needs write access to
/// `~/.mur`.
pub fn ensure_bundled_mcp_server() -> Result<PathBuf> {
    let target = bundled_mcp_server_path();
    match locate_mcp_server_source() {
        Some(src) => {
            install_if_stale(&src, &target)?;
            Ok(target)
        }
        None if target.is_file() => Ok(target),
        None => bail!(
            "mur-mcp-server not found next to `mur` or on PATH, and no copy at {}",
            target.display()
        ),
    }
}

/// The `mur-mcp-server` to copy from: sibling of `mur` first, then PATH.
fn locate_mcp_server_source() -> Option<PathBuf> {
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        let sibling = dir.join(MCP_SERVER_BIN);
        if sibling.is_file() {
            return sibling.canonicalize().ok();
        }
    }
    resolve_command(MCP_SERVER_BIN).ok()
}

/// Copy `src` to `target` unless `target` already byte-matches it. Idempotent;
/// writes via a uniquely-named temp file + rename in the target dir so the swap
/// is atomic and never leaves a half-written binary an agent might try to spawn;
/// sets mode 0755 on unix.
fn install_if_stale(src: &Path, target: &Path) -> Result<()> {
    if target.is_file() && sha256_file(src)? == sha256_file(target)? {
        return Ok(());
    }
    let dir = target
        .parent()
        .ok_or_else(|| anyhow::anyhow!("target {} has no parent", target.display()))?;
    std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    // Unique temp name so two agents starting at once don't clobber each other.
    let tmp = dir.join(format!(".{MCP_SERVER_BIN}.{}.tmp", std::process::id()));
    std::fs::copy(src, &tmp)
        .with_context(|| format!("copy {} -> {}", src.display(), tmp.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
            .with_context(|| format!("chmod {}", tmp.display()))?;
    }
    std::fs::rename(&tmp, target)
        .with_context(|| format!("rename {} -> {}", tmp.display(), target.display()))?;
    Ok(())
}

/// Stream-hash `path` SHA-256 (64 KiB chunks; lowercase hex).
fn sha256_file(path: &Path) -> Result<String> {
    use std::io::Read;
    let mut f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 65536];
    loop {
        let n = f
            .read(&mut buf)
            .with_context(|| format!("read {}", path.display()))?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hex::encode(hasher.finalize()))
}

/// Launchers that run *other* code: hashing one of these tells you nothing
/// about the MCP server it starts.
const INTERPRETERS: &[&str] = &[
    "npx", "node", "bunx", "bun", "deno", "python", "python3", "uv", "uvx", "pipx", "ruby", "perl",
    "sh", "bash", "zsh",
];

/// Whether `command` launches an MCP server through an interpreter or package
/// runner rather than being the server binary itself.
///
/// This decides whether a `binary_sha256` pin means anything. For
/// `command: npx, args: @yawlabs/fetch-mcp` the pin hashes **npx** — so it
/// breaks on every unrelated Node upgrade while saying nothing at all about
/// `@yawlabs/fetch-mcp`, which npx resolves and may fetch fresh at run time.
/// Enforcing such a pin is both fragile and hollow; the honest report is that
/// the server code is unprotected.
///
/// Real coverage for these needs a package-level pin (version + integrity),
/// which is a different mechanism than hashing a file on disk.
pub fn is_interpreter_command(command: &str) -> bool {
    let first = command.split_whitespace().next().unwrap_or(command);
    let stem = Path::new(first)
        .file_stem() // also strips .exe / .cmd on Windows
        .and_then(|s| s.to_str())
        .unwrap_or(first);
    INTERPRETERS.contains(&stem.to_ascii_lowercase().as_str())
}

/// Resolve `command` to an absolute path on disk.
///
/// - If `command` is already absolute or contains a path separator, canonicalize
///   it (resolves symlinks).
/// - Otherwise consult [`augmented_path_var`] (and try a `.exe` suffix on
///   Windows). Returns the first match found, canonicalized.
///
/// Resolving against the AUGMENTED PATH — not the raw ambient one — is what
/// keeps install-time and runtime agreeing. `mur agent mcp add` / addon import
/// run under whatever PATH their parent had: a terminal has `~/.local/bin`, a
/// Hub-spawned sidecar does not. The runtime always spawns against
/// `augmented_path_var`, so a raw-PATH resolve here made `command: uvx`
/// installable from a shell and "could not find `uvx` on PATH" from the Hub —
/// the same entry, two answers. Ambient entries still keep priority, so this
/// only ever finds MORE binaries, never a different one.
///
/// Returns an error if the binary can't be located.
pub fn resolve_command(command: &str) -> Result<PathBuf> {
    resolve_command_in(&augmented_path_var(), command)
}

/// [`resolve_command`] against an explicit PATH value instead of the ambient
/// env. The runtime resolves MCP commands against [`augmented_path_var`] for
/// BOTH the B0 admission checks and the actual spawn, so the file that gets
/// hashed is provably the file that gets exec'd.
pub fn resolve_command_in(path_var: &std::ffi::OsStr, command: &str) -> Result<PathBuf> {
    let p = Path::new(command);
    if p.is_absolute() || command.contains('/') || command.contains('\\') {
        return p
            .canonicalize()
            .with_context(|| format!("canonicalize {command}"));
    }
    for dir in std::env::split_paths(path_var) {
        let candidate = dir.join(command);
        if candidate.is_file() {
            return candidate
                .canonicalize()
                .with_context(|| format!("canonicalize {}", candidate.display()));
        }
        #[cfg(target_os = "windows")]
        {
            let with_exe = dir.join(format!("{command}.exe"));
            if with_exe.is_file() {
                return with_exe
                    .canonicalize()
                    .with_context(|| format!("canonicalize {}", with_exe.display()));
            }
        }
    }
    bail!(
        "could not find `{command}` on PATH (searched: {})",
        std::env::split_paths(path_var)
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );
}

/// The ambient PATH plus the well-known install dirs that GUI/launchd parents
/// omit (`/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`).
///
/// MCP entries store the command as the user typed it (`node`, `uvx`,
/// `python3`); which binary that names must not depend on WHO spawned the
/// runtime. A terminal hands it the user's full PATH and
/// `mur agent install-service` derives a rich one into the unit file — but a
/// Hub-spawned sidecar inherits the GUI's minimal PATH, which is how
/// `command: node` works in a shell and dies under the Hub with nothing
/// pointing here. Ambient entries keep priority; only missing standard dirs
/// are appended, so an explicit PATH override still wins.
pub fn augmented_path_var() -> std::ffi::OsString {
    let current = std::env::var_os("PATH").unwrap_or_default();
    let mut dirs_list: Vec<PathBuf> = std::env::split_paths(&current).collect();
    let mut extras: Vec<PathBuf> = vec![
        PathBuf::from("/opt/homebrew/bin"),
        PathBuf::from("/usr/local/bin"),
    ];
    if let Some(home) = dirs::home_dir() {
        extras.push(home.join(".local/bin"));
    }
    for e in extras {
        if !dirs_list.contains(&e) {
            dirs_list.push(e);
        }
    }
    std::env::join_paths(dirs_list).unwrap_or(current)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn interpreter_commands_are_recognised_including_paths_and_args() {
        for c in [
            "npx",
            "node",
            "python3",
            "uvx",
            "bunx",
            "deno",
            "sh",
            "/opt/homebrew/bin/npx",
            "npx @yawlabs/fetch-mcp",
            "NPX",
            "npx.cmd",
        ] {
            assert!(
                is_interpreter_command(c),
                "`{c}` should count as an interpreter"
            );
        }
    }

    #[test]
    fn real_server_binaries_are_not_interpreters() {
        for c in [
            "mur-mcp-server",
            "/Users/x/.mur/mcp-servers/mur-mcp-server",
            "agent-browser",
            "mur-research-gateway",
            "nodemon-ish",
        ] {
            assert!(!is_interpreter_command(c), "`{c}` is the server itself");
        }
    }

    #[test]
    fn errors_on_missing_binary() {
        assert!(resolve_command("definitely-not-a-real-binary-xyz123").is_err());
    }

    /// Regression: `mur agent mcp add` / addon import resolved against the RAW
    /// ambient PATH while the runtime spawned against the augmented one, so
    /// `command: uvx` installed fine from a terminal (whose PATH lists
    /// `~/.local/bin`) and failed with "could not find `uvx` on PATH" under the
    /// Hub, whose sidecar inherits the GUI's minimal PATH. Same entry, two
    /// answers.
    ///
    /// The test plants a binary in a standard dir that the ambient PATH does
    /// NOT list, then resolves under that minimal PATH — the Hub's situation
    /// exactly. Only an augmented-PATH resolve finds it.
    #[cfg(unix)]
    #[test]
    fn install_time_resolve_finds_binaries_the_ambient_path_omits() {
        use std::os::unix::fs::PermissionsExt;

        let home = tempfile::tempdir().unwrap();
        let local_bin = home.path().join(".local/bin");
        std::fs::create_dir_all(&local_bin).unwrap();
        let tool = local_bin.join("uvx-fixture");
        std::fs::write(&tool, "#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();

        // The Hub's PATH: /usr/bin and /bin, no ~/.local/bin. HOME is what
        // `augmented_path_var` appends `.local/bin` to, so point it at the
        // fixture.
        let mut envg = crate::test_env::EnvGuard::hold();
        envg.set_var("PATH", "/usr/bin:/bin");
        envg.set_var("HOME", home.path());

        assert!(
            resolve_command_in(
                &std::env::var_os("PATH").unwrap(),
                tool.file_name().unwrap().to_str().unwrap()
            )
            .is_err(),
            "fixture must be off the raw ambient PATH, or this proves nothing"
        );

        let resolved = resolve_command(tool.file_name().unwrap().to_str().unwrap())
            .expect("install-time resolve must search ~/.local/bin like the runtime does");
        assert_eq!(resolved, tool.canonicalize().unwrap());
    }

    #[cfg(unix)]
    #[test]
    fn resolves_bare_program_on_path_to_absolute() {
        // The whole point: a bare program name resolves to an absolute path.
        // (The runtime pin check used to open it relative to CWD and soft-fail.)
        let resolved = resolve_command("sh").expect("sh is on PATH");
        assert!(
            resolved.is_absolute(),
            "expected absolute, got {resolved:?}"
        );
        assert!(resolved.exists());
    }

    #[test]
    fn absolute_path_is_canonicalized() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let resolved = resolve_command(tmp.path().to_str().unwrap()).unwrap();
        assert!(resolved.is_absolute());
    }

    #[test]
    fn augmented_path_appends_standard_dirs_without_reordering_ambient() {
        // Read-only against the ambient env (other tests resolve on PATH in
        // parallel, so no set_var here).
        let ambient: Vec<PathBuf> =
            std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();
        let aug: Vec<PathBuf> = std::env::split_paths(&augmented_path_var()).collect();
        assert!(
            aug.starts_with(&ambient),
            "ambient PATH must keep priority: {aug:?}"
        );
        for d in ["/opt/homebrew/bin", "/usr/local/bin"] {
            let d = PathBuf::from(d);
            let in_ambient = ambient.iter().filter(|x| **x == d).count();
            let in_aug = aug.iter().filter(|x| **x == d).count();
            // Appended when absent; an ambient PATH that already lists it
            // (even more than once) is passed through untouched.
            assert_eq!(
                in_aug,
                in_ambient.max(1),
                "{d:?}: expected append-only-when-absent"
            );
        }
    }

    #[test]
    fn resolve_command_in_uses_the_given_path_not_the_env() {
        let dir = tempfile::tempdir().unwrap();
        let exe = dir.path().join("fake-mcp");
        std::fs::write(&exe, b"#!/bin/sh\n").unwrap();
        let var = std::env::join_paths([dir.path().to_path_buf()]).unwrap();
        let found = resolve_command_in(&var, "fake-mcp").unwrap();
        assert_eq!(found, exe.canonicalize().unwrap());
        assert!(
            resolve_command_in(std::ffi::OsStr::new(""), "fake-mcp").is_err(),
            "an empty path var must not fall back to the ambient PATH"
        );
    }

    #[test]
    fn install_if_stale_copies_then_is_idempotent_and_updates() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src-bin");
        let target = dir.path().join("mcp-servers/mur-mcp-server"); // parent must be created
        std::fs::write(&src, b"v1").unwrap();

        // Missing target -> copied.
        install_if_stale(&src, &target).unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"v1");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&target).unwrap().permissions().mode();
            assert_eq!(mode & 0o111, 0o111, "target must be executable");
        }

        // Unchanged source -> no-op, still v1.
        install_if_stale(&src, &target).unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"v1");

        // Updated source -> refreshed.
        std::fs::write(&src, b"v2-newer").unwrap();
        install_if_stale(&src, &target).unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"v2-newer");
    }
}