Skip to main content

mur_common/agent/
mcp.rs

1use super::*;
2
3#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
4pub struct McpServerEntry {
5    pub name: String,
6    pub command: String,
7    #[serde(default)]
8    pub args: Vec<String>,
9
10    /// SHA-256 (hex, lowercase) of the binary at `command`'s resolved
11    /// path, captured at install time. `None` means the entry was
12    /// added before B0 M9.1 (back-compat) and rule-6 enforcement is
13    /// not applied — the supervisor will warn but not block.
14    /// (B0 rule 6 / M9.1)
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub binary_sha256: Option<String>,
17
18    /// SHA-256 (hex, lowercase) of the canonical-JSON of the MCP's
19    /// `tools/list` response, captured at install time. `None` means
20    /// the install path skipped the description probe (e.g. the MCP
21    /// uses a non-stdio transport or the binary couldn't be reached)
22    /// or the entry pre-dates M9. (B0 rule 6 / M9.1)
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub description_hash: Option<String>,
25
26    /// Display-only publisher metadata captured at install time so
27    /// the user can recall what they consented to. `None` for older
28    /// entries. (B0 rule 6 / M9.1)
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub publisher: Option<McpPublisherInfo>,
31
32    /// RFC3339 timestamp of when the entry was added or last
33    /// re-approved by the user via `mur agent mcp pin`. Used by the
34    /// rug-pull dialog UX. `None` for older entries. (B0 rule 6 / M9.1)
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
37
38    /// Per-tool-call timeout for this server, in seconds. `None` uses the
39    /// runtime default. Slow tools (e.g. `video_analyze`: transcript fetch
40    /// + local-model map-reduce) need a longer budget than the default.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub timeout_secs: Option<u32>,
43
44    /// Per-server outbound egress override. `None` = inherit the agent-level
45    /// policy (default; unchanged behavior). `Restricted` routes this server's
46    /// child through the runtime egress proxy with `allow_hosts` (advisory).
47    /// See `docs/superpowers/plans/2026-06-26-mcp-per-server-egress.md`.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub network: Option<McpServerNetwork>,
50
51    /// HTTP(S) base URL for a remote (Streamable-HTTP or SSE) MCP server.
52    /// Mutually exclusive with `command` in practice; `None` = stdio transport.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub url: Option<String>,
55
56    /// Authentication credentials for a remote MCP server.
57    /// `None` = no auth (or stdio transport).
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub auth: Option<McpAuth>,
60
61    /// External programs this artifact needs at runtime (portable-deps spec).
62    /// Absent → empty; resolved by `mur agent/fleet doctor` + `install-deps`.
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    pub requires_programs: Vec<ProgramDep>,
65
66    /// Paths this server writes state into at runtime, declared at install
67    /// time so the sandbox can be told about them (issue #1161).
68    ///
69    /// Distinct from everything above: `command`, `args` and `package`
70    /// describe how the server is *launched*, and #1158 already syncs what the
71    /// rewritten launch line needs. These are what the server touches once it
72    /// is running — a property of the server, not of the command MUR rewrote.
73    /// `@wonderwhy-er/desktop-commander` wants three of them under `$HOME` and
74    /// exits 1 before answering `initialize` without them.
75    ///
76    /// Granted read+write, and **created if missing** at install time. The
77    /// sandbox drops entitlement paths that do not exist when the profile is
78    /// sealed, so granting a directory the server has not created yet would be
79    /// accepted and still denied by the kernel — see `reject_dead_grant`.
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub state_paths: Vec<String>,
82
83    /// Vendored package this entry launches, when MUR installed it itself.
84    ///
85    /// Present only for entries moved off a package runner by
86    /// `mur agent mcp vendor`. Its existence is what makes the contents of an
87    /// interpreter-launched server verifiable at all: `npx @scope/pkg` resolves
88    /// on every spawn and pins nothing, whereas a vendored install lives in a
89    /// directory MUR owns and can be checked before the agent comes up.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub package: Option<McpPackagePin>,
92}
93
94/// A package MUR installed itself, and the fingerprint that proves the
95/// installed tree hasn't changed.
96///
97/// `lockfile_sha256` hashes the install's `package-lock.json`, which already
98/// records an integrity hash for every package in the dependency tree — so one
99/// small file covers the whole tree, and startup verification stays cheap no
100/// matter how large `node_modules` grows.
101///
102/// The lockfile pins what was *installed*. Editing a file inside
103/// `node_modules` afterwards would not change it; catching that needs a full
104/// tree hash, which is deliberately not done here — see the module docs on
105/// `mur-core::cmd::agent_mcp_vendor` for where that line is drawn.
106#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
107pub struct McpPackagePin {
108    /// Package ecosystem — `npm` today.
109    pub runner: String,
110    /// Package name, including any `@scope/` prefix.
111    pub name: String,
112    /// Exact installed version.
113    pub version: String,
114    /// Directory MUR installed into, absolute.
115    pub install_dir: String,
116    /// SHA-256 (lowercase hex) of `<install_dir>/package-lock.json`.
117    pub lockfile_sha256: String,
118
119    /// How many packages in the installed tree published no registry
120    /// signature, as reported by `npm audit signatures` at vendor time.
121    ///
122    /// `None` — the audit did not run (npm too old, or offline).
123    /// `Some(0)` — every package in the tree carried a verified signature.
124    /// `Some(n)` — `n` packages are unsigned; the rest verified.
125    ///
126    /// A signature that verifies proves the bytes came from the registry, which
127    /// the content hash cannot: it would faithfully pin a poisoned cache. An
128    /// *invalid* signature is not recorded here because it blocks the vendor
129    /// outright — that is an integrity failure, not a property to note.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub signatures_missing: Option<u32>,
132
133    /// SLSA predicate type of the package's build provenance, when it
134    /// publishes one — e.g. `https://slsa.dev/provenance/v1`. `None` means no
135    /// attestation was published (still the common case).
136    ///
137    /// Provenance ties a release back to a source repository and CI run, and
138    /// is the only signal here that can catch a **malicious publish**: a
139    /// content hash pins whatever was released, faithfully preserving a
140    /// poisoned version rather than detecting it. Recorded and shown, never
141    /// required — ecosystem coverage is far too thin to gate on.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub provenance: Option<String>,
144}
145
146impl McpPackagePin {
147    /// Name of the lockfile whose hash is `lockfile_sha256`.
148    ///
149    /// npm writes `package-lock.json` itself; for PyPI, MUR generates one with
150    /// `uv pip compile --generate-hashes`, which records a sha256 for every
151    /// package in the resolved tree — the same property that lets one small
152    /// file stand in for the whole install.
153    pub fn lockfile_name(&self) -> &'static str {
154        match self.runner.as_str() {
155            "pypi" => "requirements.lock",
156            _ => "package-lock.json",
157        }
158    }
159
160    /// Absolute path of the lockfile this pin covers.
161    ///
162    /// The startup check, `inspect`, and the deep audit all resolve it through
163    /// here, so a newly supported ecosystem cannot end up verified against the
164    /// wrong file in one of them and silently pass.
165    pub fn lockfile_path(&self) -> std::path::PathBuf {
166        std::path::Path::new(&self.install_dir).join(self.lockfile_name())
167    }
168}
169
170/// Authentication scheme for a remote (HTTP) MCP server.
171#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
172#[serde(rename_all = "snake_case", tag = "kind")]
173pub enum McpAuth {
174    /// Static bearer token stored as a secret reference.
175    Bearer { token: crate::secret::SecretRef },
176    /// OAuth 2.1 token, with dynamic client registration state.
177    Oauth(OauthAuth),
178}
179
180/// OAuth 2.1 state persisted alongside remote MCP entry.
181#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
182pub struct OauthAuth {
183    /// Authorization-server token endpoint (from discovery).
184    pub token_endpoint: String,
185    /// Client id from dynamic client registration.
186    pub client_id: String,
187    /// Keychain ref to access token.
188    pub access_token: crate::secret::SecretRef,
189    /// Keychain ref refresh token, if server issued one.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub refresh_token: Option<crate::secret::SecretRef>,
192    /// Unix-epoch seconds access token expires (0 = unknown).
193    #[serde(default)]
194    pub expires_at: u64,
195}
196
197/// How an MCP server's outbound network is scoped.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
199#[serde(rename_all = "snake_case")]
200pub enum McpNetMode {
201    /// No per-server policy and no proxy — the default.
202    ///
203    /// NOT "inherits `entitlements.network.outbound.allow_hosts`", despite the
204    /// name. That list is enforced in-process (a DNS guard on the runtime's own
205    /// HTTP client, plus the B0 gate on the agent's `network.*` tools), and a
206    /// spawned server never runs either. What a server here actually inherits
207    /// is the OS sandbox — which restricts by PORT, with the host left open.
208    ///
209    /// So an agent whose `allow_hosts` names one API still lets an `Inherit`
210    /// server reach any host on an allowed port. Use `Restricted` to bound a
211    /// server by host. The variant keeps its name because it is a serialized
212    /// wire value; the lie was the doc, and it is fixed here rather than
213    /// migrated.
214    #[default]
215    Inherit,
216    /// Allow only `allow_hosts`, routed through the runtime egress proxy.
217    Restricted,
218    /// Allow ALL hosts EXCEPT `deny_hosts`, routed through the runtime egress
219    /// proxy, with every CONNECT audited. For trusted-but-broad tools (e.g. a
220    /// web-research browser) that cannot enumerate their destinations. Requires
221    /// explicit operator consent (records `authorization`); downgraded to
222    /// `Inherit` on import (lowest trust). Advisory enforcement (see egress_proxy).
223    BroadAudited,
224    /// No outbound for this server at all.
225    Off,
226}
227
228/// Env var name a sandboxed MCP child reads to self-enforce the operator's
229/// `deny_hosts` overlay on connections the egress proxy cannot observe (e.g.
230/// `mur-research-gateway`'s tier-2/3 browser subprocesses — the proxy only
231/// sees tier-1 `reqwest` traffic). `mur-agent-runtime`'s `proxy_env_for` sets
232/// this on the child's env alongside the proxy vars; a cooperating child
233/// (currently `mur-research-gateway`, via `config::load`) reads it to source
234/// its own deny list. Single definition shared by both crates (CLAUDE.md
235/// rule 1: no duplicated literal).
236pub const ENV_MCP_DENY_HOSTS: &str = "MUR_RESEARCH_DENY_HOSTS";
237
238/// Per-MCP-server outbound egress policy.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
240pub struct McpServerNetwork {
241    #[serde(default)]
242    pub mode: McpNetMode,
243    #[serde(default)]
244    pub allow_hosts: Vec<String>,
245    /// Deny overlay for `BroadAudited` mode: hosts blocked even though all
246    /// others are allowed. Ignored by `Restricted`/`Inherit`/`Off`.
247    #[serde(default)]
248    pub deny_hosts: Vec<String>,
249    /// Who authorized a `BroadAudited` grant, and when. `None` for other modes.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub authorization: Option<EgressAuthorization>,
252}
253
254/// True when any of `entries` declares a scoped network policy
255/// (`Restricted` / `BroadAudited`) — i.e. it must be spawned behind the
256/// loopback egress proxy with a tokened `HTTPS_PROXY`.
257///
258/// The single source for that decision. The runtime calls it before the
259/// kernel sandbox seals (so the proxy port can be carved into the profile);
260/// `mur agent mcp add`'s live probe calls it to decide whether the probe child
261/// needs a proxy at all. Both must agree, or a server that passes the probe
262/// fails under the runtime (or vice versa) — which is why it lives here and
263/// not in either caller.
264pub fn entries_need_egress(entries: &[McpServerEntry]) -> bool {
265    entries.iter().any(|e| {
266        matches!(
267            e.network.as_ref().map(|n| n.mode),
268            Some(McpNetMode::Restricted) | Some(McpNetMode::BroadAudited)
269        )
270    })
271}
272
273/// A plugin-group imported by one agent (add-on Phase 2). Self-contained:
274/// members are installed PER-AGENT (skills under
275/// `~/.mur/agents/<a>/skills/`, mcp appended to this profile's
276/// `mcp_servers`). No global library, no refcounting.
277///
278/// Fail-closed: `enabled` defaults to `false`. Only an explicit user
279/// toggle (CLI/Hub) or a trusted native installer flips it true — the
280/// importer always constructs it `false`.
281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
282pub struct AddonRef {
283    /// e.g. "superpowers" (local) or "superpowers@claude-plugins-official".
284    pub id: String,
285    /// Provenance, free-text. e.g. "claude-local:superpowers@6.0.3".
286    pub source: String,
287    #[serde(default)]
288    pub enabled: bool,
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub skills: Vec<String>,
291    #[serde(default, skip_serializing_if = "Vec::is_empty")]
292    pub mcp: Vec<String>,
293    #[serde(default, skip_serializing_if = "Vec::is_empty")]
294    pub commands: Vec<String>,
295    /// Content-hash pin over the imported skill/command manifests, recorded
296    /// at import. `None` on legacy refs. Enables drift detection + refresh.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub content_hash: Option<String>,
299    /// The re-fetchable source (the original `import` argument: a local path
300    /// or `owner/repo`), distinct from the free-text provenance `source`.
301    /// `None` on legacy refs. Used by `reimport`.
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub fetch_ref: Option<String>,
304    /// The `--plugin <name>` selector used at import time to pick one plugin
305    /// out of a multi-plugin marketplace `fetch_ref`. `None` when the source
306    /// was a single-plugin dir/repo, or on legacy refs. Used by `reimport` so
307    /// a marketplace add-on can be re-fetched without re-specifying it.
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub fetch_plugin: Option<String>,
310}
311
312/// Display-only publisher metadata captured at install time. None of
313/// the fields are validated against any external authority — they're
314/// shown to the user during the install confirm prompt and reproduced
315/// in `mur agent mcp inspect` output so the user can audit who they
316/// thought they were trusting. (B0 rule 6 / M9.1)
317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
318pub struct McpPublisherInfo {
319    /// Free-form publisher identifier — e.g. `"Anthropic"`,
320    /// `"@github-user-alice"`, or whatever `serverInfo.name` returned.
321    pub name: String,
322
323    /// Optional homepage / docs URL. Best-effort: extracted from the
324    /// MCP's `serverInfo.metadata.homepage` or registry entry when
325    /// available; otherwise left unset.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub homepage: Option<String>,
328
329    /// Optional registry coordinate — e.g. `"@anthropic-mcp/weather@1.2.3"`.
330    /// Used purely for display; not consumed by any verification path.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub registry_id: Option<String>,
333}
334
335#[cfg(test)]
336mod mcp_pin_tests {
337    use super::*;
338
339    /// Pre-M9 profiles must continue to deserialize with the new
340    /// optional fields absent. Round-trip: serialize back out and
341    /// confirm the optional fields don't leak into the YAML.
342    #[test]
343    fn pre_m9_entry_roundtrips_without_pin_fields() {
344        let yaml = r#"
345name: weather
346command: /opt/mcp/weather
347args: ["--port", "0"]
348"#;
349        let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
350        assert_eq!(entry.name, "weather");
351        assert_eq!(entry.binary_sha256, None);
352        assert_eq!(entry.description_hash, None);
353        assert_eq!(entry.publisher, None);
354        assert_eq!(entry.installed_at, None);
355
356        // skip_serializing_if = "Option::is_none" must keep the YAML
357        // free of empty pin fields when the entry is pre-M9.
358        let out = serde_yaml_ng::to_string(&entry).unwrap();
359        assert!(!out.contains("binary_sha256"), "got {out}");
360        assert!(!out.contains("description_hash"), "got {out}");
361        assert!(!out.contains("publisher"), "got {out}");
362        assert!(!out.contains("installed_at"), "got {out}");
363    }
364
365    /// Full M9 entry with all fields set round-trips losslessly.
366    #[test]
367    fn full_m9_entry_roundtrips_all_fields() {
368        let yaml = r#"
369name: weather
370command: /opt/mcp/weather
371args: []
372binary_sha256: "3f4abca8b0e6e2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b81c"
373description_hash: "9a01b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9c7e2"
374publisher:
375  name: "@anthropic-mcp/weather"
376  homepage: "https://github.com/anthropic-mcp/weather"
377  registry_id: "@anthropic-mcp/weather@1.2.3"
378installed_at: "2026-05-06T08:00:00Z"
379"#;
380        let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
381        assert!(
382            entry
383                .binary_sha256
384                .as_deref()
385                .unwrap()
386                .starts_with("3f4abca8")
387        );
388        assert!(
389            entry
390                .description_hash
391                .as_deref()
392                .unwrap()
393                .starts_with("9a01b2c3")
394        );
395        let pub_info = entry.publisher.clone().unwrap();
396        assert_eq!(pub_info.name, "@anthropic-mcp/weather");
397        assert_eq!(
398            pub_info.homepage.as_deref(),
399            Some("https://github.com/anthropic-mcp/weather"),
400        );
401        assert_eq!(
402            pub_info.registry_id.as_deref(),
403            Some("@anthropic-mcp/weather@1.2.3"),
404        );
405        let installed = entry.installed_at.unwrap();
406        assert_eq!(installed.to_rfc3339(), "2026-05-06T08:00:00+00:00");
407    }
408
409    /// Partial — only the binary hash is set (e.g. probe failed but
410    /// install proceeded). The supervisor still needs to be able to
411    /// deserialize this without panicking.
412    #[test]
413    fn partial_pin_only_binary_sha_roundtrips() {
414        let yaml = r#"
415name: weather
416command: /opt/mcp/weather
417args: []
418binary_sha256: "deadbeef00112233445566778899aabbccddeeff00112233445566778899aabb"
419"#;
420        let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
421        assert_eq!(
422            entry.binary_sha256.as_deref(),
423            Some("deadbeef00112233445566778899aabbccddeeff00112233445566778899aabb"),
424        );
425        assert_eq!(entry.description_hash, None);
426        assert_eq!(entry.publisher, None);
427    }
428
429    /// Publisher with only the required `name` field — homepage and
430    /// registry_id are optional.
431    #[test]
432    fn publisher_minimal_just_name() {
433        let yaml = r#"
434name: weather
435command: /opt/mcp/weather
436args: []
437publisher:
438  name: "alice"
439"#;
440        let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
441        let p = entry.publisher.as_ref().unwrap();
442        assert_eq!(p.name, "alice");
443        assert_eq!(p.homepage, None);
444        assert_eq!(p.registry_id, None);
445
446        // skip_serializing_if must omit the optional sub-fields too.
447        let out = serde_yaml_ng::to_string(&entry).unwrap();
448        assert!(!out.contains("homepage:"), "got {out}");
449        assert!(!out.contains("registry_id:"), "got {out}");
450    }
451}
452
453#[cfg(test)]
454mod remote_mcp_tests {
455    use super::*;
456
457    #[test]
458    fn mcp_entry_roundtrips_remote_bearer() {
459        let e = McpServerEntry {
460            name: "gh".into(),
461            command: String::new(),
462            url: Some("https://api.example.com/mcp".into()),
463            auth: Some(McpAuth::Bearer {
464                token: crate::secret::SecretRef::Env("GH_TOKEN".into()),
465            }),
466            ..Default::default()
467        };
468        let y = serde_yaml_ng::to_string(&e).unwrap();
469        let back: McpServerEntry = serde_yaml_ng::from_str(&y).unwrap();
470        assert_eq!(back.url.as_deref(), Some("https://api.example.com/mcp"));
471        assert!(matches!(
472            back.auth,
473            Some(McpAuth::Bearer { ref token }) if *token == crate::secret::SecretRef::Env("GH_TOKEN".into())
474        ));
475        // A legacy stdio entry (no url/auth) still parses.
476        let legacy: McpServerEntry =
477            serde_yaml_ng::from_str("name: fs\ncommand: npx\nargs: [\"-y\",\"fs\"]\n").unwrap();
478        assert!(legacy.url.is_none());
479        assert!(legacy.auth.is_none());
480    }
481}
482
483#[cfg(test)]
484mod requires_programs_tests {
485    #[test]
486    fn mcp_entry_parses_requires_programs_and_defaults_empty() {
487        let with = r#"
488name: research-gateway
489command: mur-research-gateway
490requires_programs:
491  - name: lightpanda
492    detect: { file: "~/.mur/aura/lightpanda" }
493    reason: "render tier"
494    registry: lightpanda
495"#;
496        let e: crate::agent::McpServerEntry = serde_yaml::from_str(with).unwrap();
497        assert_eq!(e.requires_programs.len(), 1);
498        assert_eq!(e.requires_programs[0].name, "lightpanda");
499
500        // Absent block → empty (back-compat).
501        let without = "name: x\ncommand: y\n";
502        let e2: crate::agent::McpServerEntry = serde_yaml::from_str(without).unwrap();
503        assert!(e2.requires_programs.is_empty());
504    }
505}
506
507#[cfg(test)]
508mod egress_need_tests {
509    #[test]
510    fn entries_need_egress_matches_scoped_modes() {
511        use super::*;
512        fn entry(mode: Option<McpNetMode>) -> McpServerEntry {
513            let mut e = McpServerEntry {
514                name: "s".into(),
515                command: "cmd".into(),
516                ..Default::default()
517            };
518            e.network = mode.map(|m| McpServerNetwork {
519                mode: m,
520                ..Default::default()
521            });
522            e
523        }
524        assert!(!entries_need_egress(&[entry(None)]));
525        assert!(!entries_need_egress(&[entry(Some(McpNetMode::Inherit))]));
526        assert!(!entries_need_egress(&[entry(Some(McpNetMode::Off))]));
527        assert!(entries_need_egress(&[entry(Some(McpNetMode::Restricted))]));
528        assert!(entries_need_egress(&[
529            entry(None),
530            entry(Some(McpNetMode::BroadAudited))
531        ]));
532    }
533}