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/// A plugin-group imported by one agent (add-on Phase 2). Self-contained:
255/// members are installed PER-AGENT (skills under
256/// `~/.mur/agents/<a>/skills/`, mcp appended to this profile's
257/// `mcp_servers`). No global library, no refcounting.
258///
259/// Fail-closed: `enabled` defaults to `false`. Only an explicit user
260/// toggle (CLI/Hub) or a trusted native installer flips it true — the
261/// importer always constructs it `false`.
262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
263pub struct AddonRef {
264 /// e.g. "superpowers" (local) or "superpowers@claude-plugins-official".
265 pub id: String,
266 /// Provenance, free-text. e.g. "claude-local:superpowers@6.0.3".
267 pub source: String,
268 #[serde(default)]
269 pub enabled: bool,
270 #[serde(default, skip_serializing_if = "Vec::is_empty")]
271 pub skills: Vec<String>,
272 #[serde(default, skip_serializing_if = "Vec::is_empty")]
273 pub mcp: Vec<String>,
274 #[serde(default, skip_serializing_if = "Vec::is_empty")]
275 pub commands: Vec<String>,
276 /// Content-hash pin over the imported skill/command manifests, recorded
277 /// at import. `None` on legacy refs. Enables drift detection + refresh.
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub content_hash: Option<String>,
280 /// The re-fetchable source (the original `import` argument: a local path
281 /// or `owner/repo`), distinct from the free-text provenance `source`.
282 /// `None` on legacy refs. Used by `reimport`.
283 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub fetch_ref: Option<String>,
285 /// The `--plugin <name>` selector used at import time to pick one plugin
286 /// out of a multi-plugin marketplace `fetch_ref`. `None` when the source
287 /// was a single-plugin dir/repo, or on legacy refs. Used by `reimport` so
288 /// a marketplace add-on can be re-fetched without re-specifying it.
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub fetch_plugin: Option<String>,
291}
292
293/// Display-only publisher metadata captured at install time. None of
294/// the fields are validated against any external authority — they're
295/// shown to the user during the install confirm prompt and reproduced
296/// in `mur agent mcp inspect` output so the user can audit who they
297/// thought they were trusting. (B0 rule 6 / M9.1)
298#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
299pub struct McpPublisherInfo {
300 /// Free-form publisher identifier — e.g. `"Anthropic"`,
301 /// `"@github-user-alice"`, or whatever `serverInfo.name` returned.
302 pub name: String,
303
304 /// Optional homepage / docs URL. Best-effort: extracted from the
305 /// MCP's `serverInfo.metadata.homepage` or registry entry when
306 /// available; otherwise left unset.
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub homepage: Option<String>,
309
310 /// Optional registry coordinate — e.g. `"@anthropic-mcp/weather@1.2.3"`.
311 /// Used purely for display; not consumed by any verification path.
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub registry_id: Option<String>,
314}
315
316#[cfg(test)]
317mod mcp_pin_tests {
318 use super::*;
319
320 /// Pre-M9 profiles must continue to deserialize with the new
321 /// optional fields absent. Round-trip: serialize back out and
322 /// confirm the optional fields don't leak into the YAML.
323 #[test]
324 fn pre_m9_entry_roundtrips_without_pin_fields() {
325 let yaml = r#"
326name: weather
327command: /opt/mcp/weather
328args: ["--port", "0"]
329"#;
330 let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
331 assert_eq!(entry.name, "weather");
332 assert_eq!(entry.binary_sha256, None);
333 assert_eq!(entry.description_hash, None);
334 assert_eq!(entry.publisher, None);
335 assert_eq!(entry.installed_at, None);
336
337 // skip_serializing_if = "Option::is_none" must keep the YAML
338 // free of empty pin fields when the entry is pre-M9.
339 let out = serde_yaml_ng::to_string(&entry).unwrap();
340 assert!(!out.contains("binary_sha256"), "got {out}");
341 assert!(!out.contains("description_hash"), "got {out}");
342 assert!(!out.contains("publisher"), "got {out}");
343 assert!(!out.contains("installed_at"), "got {out}");
344 }
345
346 /// Full M9 entry with all fields set round-trips losslessly.
347 #[test]
348 fn full_m9_entry_roundtrips_all_fields() {
349 let yaml = r#"
350name: weather
351command: /opt/mcp/weather
352args: []
353binary_sha256: "3f4abca8b0e6e2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b81c"
354description_hash: "9a01b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9c7e2"
355publisher:
356 name: "@anthropic-mcp/weather"
357 homepage: "https://github.com/anthropic-mcp/weather"
358 registry_id: "@anthropic-mcp/weather@1.2.3"
359installed_at: "2026-05-06T08:00:00Z"
360"#;
361 let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
362 assert!(
363 entry
364 .binary_sha256
365 .as_deref()
366 .unwrap()
367 .starts_with("3f4abca8")
368 );
369 assert!(
370 entry
371 .description_hash
372 .as_deref()
373 .unwrap()
374 .starts_with("9a01b2c3")
375 );
376 let pub_info = entry.publisher.clone().unwrap();
377 assert_eq!(pub_info.name, "@anthropic-mcp/weather");
378 assert_eq!(
379 pub_info.homepage.as_deref(),
380 Some("https://github.com/anthropic-mcp/weather"),
381 );
382 assert_eq!(
383 pub_info.registry_id.as_deref(),
384 Some("@anthropic-mcp/weather@1.2.3"),
385 );
386 let installed = entry.installed_at.unwrap();
387 assert_eq!(installed.to_rfc3339(), "2026-05-06T08:00:00+00:00");
388 }
389
390 /// Partial — only the binary hash is set (e.g. probe failed but
391 /// install proceeded). The supervisor still needs to be able to
392 /// deserialize this without panicking.
393 #[test]
394 fn partial_pin_only_binary_sha_roundtrips() {
395 let yaml = r#"
396name: weather
397command: /opt/mcp/weather
398args: []
399binary_sha256: "deadbeef00112233445566778899aabbccddeeff00112233445566778899aabb"
400"#;
401 let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
402 assert_eq!(
403 entry.binary_sha256.as_deref(),
404 Some("deadbeef00112233445566778899aabbccddeeff00112233445566778899aabb"),
405 );
406 assert_eq!(entry.description_hash, None);
407 assert_eq!(entry.publisher, None);
408 }
409
410 /// Publisher with only the required `name` field — homepage and
411 /// registry_id are optional.
412 #[test]
413 fn publisher_minimal_just_name() {
414 let yaml = r#"
415name: weather
416command: /opt/mcp/weather
417args: []
418publisher:
419 name: "alice"
420"#;
421 let entry: McpServerEntry = serde_yaml_ng::from_str(yaml).unwrap();
422 let p = entry.publisher.as_ref().unwrap();
423 assert_eq!(p.name, "alice");
424 assert_eq!(p.homepage, None);
425 assert_eq!(p.registry_id, None);
426
427 // skip_serializing_if must omit the optional sub-fields too.
428 let out = serde_yaml_ng::to_string(&entry).unwrap();
429 assert!(!out.contains("homepage:"), "got {out}");
430 assert!(!out.contains("registry_id:"), "got {out}");
431 }
432}
433
434#[cfg(test)]
435mod remote_mcp_tests {
436 use super::*;
437
438 #[test]
439 fn mcp_entry_roundtrips_remote_bearer() {
440 let e = McpServerEntry {
441 name: "gh".into(),
442 command: String::new(),
443 url: Some("https://api.example.com/mcp".into()),
444 auth: Some(McpAuth::Bearer {
445 token: crate::secret::SecretRef::Env("GH_TOKEN".into()),
446 }),
447 ..Default::default()
448 };
449 let y = serde_yaml_ng::to_string(&e).unwrap();
450 let back: McpServerEntry = serde_yaml_ng::from_str(&y).unwrap();
451 assert_eq!(back.url.as_deref(), Some("https://api.example.com/mcp"));
452 assert!(matches!(
453 back.auth,
454 Some(McpAuth::Bearer { ref token }) if *token == crate::secret::SecretRef::Env("GH_TOKEN".into())
455 ));
456 // A legacy stdio entry (no url/auth) still parses.
457 let legacy: McpServerEntry =
458 serde_yaml_ng::from_str("name: fs\ncommand: npx\nargs: [\"-y\",\"fs\"]\n").unwrap();
459 assert!(legacy.url.is_none());
460 assert!(legacy.auth.is_none());
461 }
462}
463
464#[cfg(test)]
465mod requires_programs_tests {
466 #[test]
467 fn mcp_entry_parses_requires_programs_and_defaults_empty() {
468 let with = r#"
469name: research-gateway
470command: mur-research-gateway
471requires_programs:
472 - name: lightpanda
473 detect: { file: "~/.mur/aura/lightpanda" }
474 reason: "render tier"
475 registry: lightpanda
476"#;
477 let e: crate::agent::McpServerEntry = serde_yaml::from_str(with).unwrap();
478 assert_eq!(e.requires_programs.len(), 1);
479 assert_eq!(e.requires_programs[0].name, "lightpanda");
480
481 // Absent block → empty (back-compat).
482 let without = "name: x\ncommand: y\n";
483 let e2: crate::agent::McpServerEntry = serde_yaml::from_str(without).unwrap();
484 assert!(e2.requires_programs.is_empty());
485 }
486}