openmoat 0.22.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor's own OS sandboxes from the same policy, and keeps a local audit log.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! `moat mcp accept | proxy | wrap | unwrap` (ADR-026).
//!
//! `accept`, `wrap` and `unwrap` are a person's commands, like `moat trust`: they
//! need a terminal and an intact lock, and the default policy denies them to
//! agents. `proxy` is what an agent host starts in place of a wrapped server.

use std::collections::BTreeSet;
use std::io::Write as _;
use std::path::Path;

use anyhow::{Result, bail};
use openmoat_hosts::Host;

use crate::cli::{McpAcceptArgs, McpUnwrapArgs, McpWrapArgs};
use crate::exit::Code;
use crate::home::Home;
use crate::install::Recorded;
use crate::integrity::{self, Lock};
use crate::mcp::tools::{self, ToolPins};
use crate::mcp::wrap::{self, Done};
use crate::mcp::{self, Change};
use crate::render::{Deferred, Named, clean};

mod gate;
mod proxy;

pub use proxy::run as proxy;

fn person_only(command: &str) -> Result<Home> {
    crate::terminal::refuse_agent(&format!("openmoat mcp {command}"))?;
    if !crate::terminal::interactive() {
        bail!(
            "`openmoat mcp {command}` must be run by a person in a terminal, not from a hook or script"
        );
    }
    let home = Home::locate()?;
    integrity::refuse_drift(&home, &format!("run `openmoat mcp {command}`"))?;
    Ok(home)
}

pub fn accept(args: &McpAcceptArgs) -> Result<Code> {
    let home = person_only("accept")?;
    let binary = crate::install::hook_binary()?;
    let mut out = Deferred::default();
    if !review_and_accept(&home, &binary, args.server.as_deref(), &mut out)? {
        let scope = args
            .server
            .as_ref()
            .map_or_else(String::new, |s| format!(" for `{s}`"));
        writeln!(
            out,
            "nothing to accept{scope}: every MCP server and tool matches what was accepted"
        )?;
    }
    out.finish()?;
    Ok(Code::Ok)
}

/// Show every pending MCP change (definitions, and tools `moat mcp proxy` holds),
/// limited to `server` when given, ask, and accept them on yes. `false` when
/// nothing was pending.
pub(super) fn review_and_accept(
    home: &Home,
    binary: &Path,
    server: Option<&str>,
    out: &mut Deferred,
) -> Result<bool> {
    let lock = Lock::load(&home.lock_path())?;
    let cwd = std::env::current_dir().ok();
    let hosts = mcp::set_up_hosts(home, binary);
    let found = mcp::review(home, &lock, &hosts, cwd.as_deref())?;
    for (path, why) in &found.unreadable {
        writeln!(
            out,
            "! cannot read {}: {why}; fix it, then run this again",
            path.display()
        )?;
    }
    let wanted = |name: &str| server.is_none_or(|s| s == name);
    let changes: Vec<Change> = found
        .changes
        .into_iter()
        .filter(|c| wanted(&c.name))
        .collect();
    let mut held: Vec<(std::path::PathBuf, ToolPins)> = tools::all(home)?
        .into_iter()
        .filter(|(_, p)| p.held_count() > 0 && wanted(&p.server))
        .collect();
    if changes.is_empty() && held.is_empty() {
        return Ok(false);
    }
    if !found.pinned {
        writeln!(
            out,
            "OpenMoat has not pinned the agents' MCP servers yet; accepting pins these:"
        )?;
    }
    for change in &changes {
        writeln!(out, "{}", change.describe())?;
        let taken = change
            .accept
            .is_some()
            .then(|| change.host.parse::<Host>().ok())
            .flatten()
            .and_then(|host| mcp::builtin_name_taken(host, &change.name));
        if let Some((provider, _)) = taken {
            writeln!(
                out,
                "! {} is the name of an MCP server {} provides itself; this server is another \
                 program, so all its results mark the session untrusted, the lists that server \
                 returns too",
                Named(&change.name),
                provider.display_name()
            )?;
        }
    }
    for (_, pins) in &held {
        for text in pins.describe_held() {
            write!(out, "{text}")?;
        }
    }
    if !super::edit::confirm(out, "Accept these changes? [y/N] ")? {
        writeln!(
            out,
            "nothing was accepted; the changed servers' and tools' calls stay refused"
        )?;
        return Ok(true);
    }
    mcp::accept(home, &changes)?;
    let mut count = 0;
    for (path, pins) in &mut held {
        count += pins.held_count();
        pins.accept_held();
        pins.save(path)?;
    }
    writeln!(
        out,
        "✔ accepted {} server definition(s) and {count} held tool(s), instructions, prompts or resources",
        changes.len()
    )?;
    // A server just added starts unchecked each time the agent starts it:
    // offer to run it through OpenMoat, Enter for yes (ADR-102).
    let added: Vec<String> = changes
        .iter()
        .filter(|c| matches!(c.kind, mcp::pins::Kind::Added))
        .map(|c| c.id.clone())
        .collect();
    if !added.is_empty() {
        super::init::mcp::ask_and_wrap(home, binary, &hosts, Some(&added), out)?;
    }
    Ok(true)
}

pub fn wrap(args: &McpWrapArgs) -> Result<Code> {
    let home = person_only("wrap")?;
    let binary = crate::install::hook_binary()?;
    let mut out = Deferred::default();
    let hosts = mcp::set_up_hosts(&home, &binary);
    let applied = wrap_servers(
        &home,
        &binary,
        &hosts,
        &args.servers,
        args.sandbox_choice(),
        args.dry_run,
        &mut out,
    )?;
    if applied.total() == 0 {
        writeln!(out, "· no stdio MCP server to wrap")?;
    }
    out.finish()?;
    Ok(applied.code(&args.servers))
}

/// What a wrap or unwrap did.
#[derive(Debug, Clone, Copy)]
pub(super) struct Applied {
    done: usize,
    by_hand: usize,
    /// Named and left as they are: a definition OpenMoat cannot put behind
    /// the proxy, or one with a change nobody accepted.
    left: usize,
}

impl Applied {
    /// Every server handled, those left to set by hand or left as they are
    /// (each named, with why) included.
    pub(super) fn total(self) -> usize {
        self.done + self.by_hand + self.left
    }

    /// Asked for by name and not done (left to set by hand, or left as it
    /// is): what was asked was not done. A sweep of every server goes on past
    /// such a server and succeeds.
    fn code(self, names: &[String]) -> Code {
        if self.by_hand + self.left > 0 && !names.is_empty() {
            Code::Usage
        } else {
            Code::Ok
        }
    }
}

/// What [`wrap_plan`] found to write.
pub(super) struct WrapPlan {
    pub(super) edits: Vec<(crate::mcp::servers::Source, Done)>,
    /// The servers named and left as they are.
    pub(super) left: usize,
}

/// Wrap the stdio servers named in `names` (all when empty) in the user
/// configuration of `hosts`; returns how many. `moat init --mcp-proxy` uses it.
/// `sandbox` is the person's choice: `None` starts a newly wrapped server in
/// `moat run`'s sandbox wherever that can sandbox, and leaves a wrapped one as
/// it is; `Some` also switches a wrapped one (ADR-049). The count includes the
/// servers in a file OpenMoat does not rewrite, which are named with what to
/// set by hand: one such file must not stop the others.
pub(super) fn wrap_servers(
    home: &Home,
    binary: &Path,
    hosts: &[Host],
    names: &[String],
    sandbox: Option<bool>,
    dry_run: bool,
    out: &mut Deferred,
) -> Result<Applied> {
    let WrapPlan { mut edits, left } = wrap_plan(home, binary, hosts, names, sandbox, out)?;
    let by_hand = drop_what_cannot_be_rewritten(&mut edits, out)?;
    let done = apply_wrap(home, hosts, &edits, sandbox, dry_run, out)?;
    Ok(Applied {
        done,
        by_hand,
        left,
    })
}

/// Take out the servers in files OpenMoat deliberately does not rewrite,
/// saying what to set by hand; how many. A file that cannot be read or
/// parsed, or no longer holds a server, fails the command.
pub(super) fn drop_what_cannot_be_rewritten(
    edits: &mut Vec<(crate::mcp::servers::Source, Done)>,
    out: &mut Deferred,
) -> Result<usize> {
    let before = edits.len();
    for preview in wrap::preview(edits)? {
        if let Err(why) = preview.change {
            writeln!(out, "! mcp servers      {why}")?;
            edits.retain(|(source, _)| source.path != preview.path);
        }
    }
    Ok(before - edits.len())
}

/// What wrapping the stdio servers in `names` (all when empty) of `hosts`
/// would write; a definition with a change nobody accepted, or one OpenMoat
/// cannot put behind the proxy, is named and left.
pub(super) fn wrap_plan(
    home: &Home,
    binary: &Path,
    hosts: &[Host],
    names: &[String],
    sandbox: Option<bool>,
    out: &mut Deferred,
) -> Result<WrapPlan> {
    let pending = pending_ids(home, hosts)?;
    let new_sandbox = sandbox.unwrap_or(super::run::unavailable().is_none());
    let mut edits = Vec::new();
    let mut left = 0;
    let servers = wrap::user_servers(home, hosts)?;
    left += unknown_names(&servers, names, "wrap", out)?;
    for (source, server) in servers {
        if !names.is_empty() && !names.contains(&server.name) {
            continue;
        }
        let form = server.form;
        let entry = wrap::wrapped_as(&server.entry, binary, &server.name, new_sandbox, form)
            .or_else(|| sandbox.and_then(|on| wrap::with_sandbox(&server.entry, form, on)));
        // The proxy takes only the hook decisions of the agent whose file
        // starts it; a definition wrapped before `--host` existed gets it now.
        let host = server.host;
        let entry = match entry {
            Some(entry) => Some(wrap::with_host(&entry, form, host).unwrap_or(entry)),
            None => wrap::with_host(&server.entry, form, host),
        };
        let Some(entry) = entry else {
            let why = wrap::not_wrappable(&server.entry, form).or_else(|| {
                // Asked for by name, not wrapped already, and nothing to
                // wrap: a remote server, or one naming no program.
                (!names.is_empty() && wrap::sandboxed(&server.entry, form).is_none())
                    .then_some("it runs no local command, so there is nothing to wrap")
            });
            if let Some(why) = why {
                writeln!(
                    out,
                    "! {} ({}) is left as it is: {why}",
                    Named(&server.name),
                    server.file.display()
                )?;
                left += 1;
            }
            continue;
        };
        if pending.contains(&server.id) {
            skipped(out, &server.name)?;
            left += 1;
            continue;
        }
        edits.push((source, Done { server, entry }));
    }
    Ok(WrapPlan { edits, left })
}

/// Name each of `names` that is no server of `servers` (a typo, or a server
/// of a project's file, which `moat mcp {verb}` does not change); how many.
fn unknown_names(
    servers: &[(crate::mcp::servers::Source, crate::mcp::servers::Server)],
    names: &[String],
    verb: &str,
    out: &mut Deferred,
) -> Result<usize> {
    let mut unknown = 0;
    for name in names {
        if servers.iter().any(|(_, s)| &s.name == name) {
            continue;
        }
        writeln!(
            out,
            "! {} is no MCP server in the agents' own files, so there is nothing to {verb}",
            Named(name)
        )?;
        unknown += 1;
    }
    Ok(unknown)
}

/// Write `edits` from [`wrap_plan`] and say what they mean; how many.
pub(super) fn apply_wrap(
    home: &Home,
    hosts: &[Host],
    edits: &[(crate::mcp::servers::Source, Done)],
    sandbox: Option<bool>,
    dry_run: bool,
    out: &mut Deferred,
) -> Result<usize> {
    let unavailable = super::run::unavailable();
    let done = finish_edits(home, hosts, edits, dry_run, true, out)?;
    let unavailable = unavailable.filter(|_| sandbox.is_none_or(|on| on));
    sandbox_note(edits, unavailable.as_deref(), out)?;
    first_sight_note(home, edits, out)?;
    Ok(done)
}

/// One line naming the servers just written to start without the sandbox,
/// with why (`unavailable`, unless the person chose `--no-sandbox`), and,
/// when the sandbox was asked for where `moat run` cannot sandbox, why they
/// will not start.
fn sandbox_note(
    edits: &[(crate::mcp::servers::Source, Done)],
    unavailable: Option<&str>,
    out: &mut Deferred,
) -> Result<()> {
    let names = |on: bool| -> Vec<String> {
        edits
            .iter()
            .filter(|(_, d)| wrap::sandboxed(&d.entry, d.server.form) == Some(on))
            .map(|(_, d)| Named(&d.server.name).to_string())
            .collect()
    };
    let (unconfined, confined) = (names(false), names(true));
    if !unconfined.is_empty() {
        let why =
            unavailable.map_or_else(|| " (--no-sandbox)".to_owned(), |why| format!(": {why}"));
        writeln!(
            out,
            "! {} run without `openmoat run`'s sandbox, with your permissions{why}",
            unconfined.join(", ")
        )?;
    }
    if let (Some(why), false) = (unavailable, confined.is_empty()) {
        writeln!(
            out,
            "! {} cannot start in `openmoat run`'s sandbox here ({why}); run \
             `openmoat mcp wrap --no-sandbox` to start them unconfined",
            confined.join(", ")
        )?;
    }
    Ok(())
}

/// One line on what a wrapped server with no tool pins yet does first: the
/// proxy holds every tool it lists until a person accepts them (ADR-032).
fn first_sight_note(
    home: &Home,
    edits: &[(crate::mcp::servers::Source, Done)],
    out: &mut Deferred,
) -> Result<()> {
    if home
        .load_policy()
        .is_ok_and(|policy| policy.trust_mcp_first_sight())
    {
        return Ok(());
    }
    let new: BTreeSet<&str> = edits
        .iter()
        .map(|(_, done)| done.server.name.as_str())
        .filter(|name| !tools::path(home, name).exists())
        .collect();
    if new.is_empty() {
        return Ok(());
    }
    let names: Vec<String> = new.iter().map(|n| Named(n).to_string()).collect();
    writeln!(
        out,
        "· the tools of {} wait for `openmoat mcp accept <server>` after the server's first start",
        names.join(", ")
    )?;
    Ok(())
}

pub fn unwrap(args: &McpUnwrapArgs) -> Result<Code> {
    let home = person_only("unwrap")?;
    let binary = crate::install::hook_binary()?;
    let mut out = Deferred::default();
    let hosts = mcp::set_up_hosts(&home, &binary);
    let applied = unwrap_servers(&home, &hosts, &args.servers, &mut out)?;
    if applied.total() == 0 {
        writeln!(out, "· no wrapped MCP server to unwrap")?;
    }
    out.finish()?;
    Ok(applied.code(&args.servers))
}

/// Unwrap the servers named in `names`, or every one `hosts.json` records as
/// wrapped when empty; returns how many. `moat uninstall` uses it.
pub(super) fn unwrap_servers(
    home: &Home,
    hosts: &[Host],
    names: &[String],
    out: &mut Deferred,
) -> Result<Applied> {
    let recorded = Recorded::load(home)?;
    let pending = pending_ids(home, hosts)?;
    let mut edits = Vec::new();
    let mut left = 0;
    let servers = wrap::user_servers(home, hosts)?;
    left += unknown_names(&servers, names, "unwrap", out)?;
    for (source, server) in servers {
        let chosen = if names.is_empty() {
            recorded
                .mcp_wrapped
                .iter()
                .any(|w| w.file == server.file && w.pointer == server.pointer)
        } else {
            names.contains(&server.name)
        };
        let Some(entry) = wrap::unwrapped(&server.entry, server.form).filter(|_| chosen) else {
            continue;
        };
        if pending.contains(&server.id) {
            skipped(out, &server.name)?;
            left += 1;
            continue;
        }
        edits.push((source, Done { server, entry }));
    }
    let by_hand = drop_what_cannot_be_rewritten(&mut edits, out)?;
    let done = finish_edits(home, hosts, &edits, false, false, out)?;
    Ok(Applied {
        done,
        by_hand,
        left,
    })
}

fn skipped(out: &mut Deferred, name: &str) -> Result<()> {
    writeln!(
        out,
        "! skipped {}: its definition changed since it was accepted; \
         run `openmoat mcp accept {}` first",
        Named(name),
        clean(name)
    )?;
    Ok(())
}

/// Ids of definitions with a change nobody accepted: rewriting one and
/// re-pinning it would accept that change unseen.
fn pending_ids(home: &Home, hosts: &[Host]) -> Result<BTreeSet<String>> {
    let path = home.lock_path();
    if !path.is_file() {
        return Ok(BTreeSet::new());
    }
    let lock = Lock::load(&path)?;
    if lock.mcp_servers.is_none() {
        return Ok(BTreeSet::new());
    }
    let found = mcp::review(home, &lock, hosts, None)?;
    Ok(found.changes.into_iter().map(|c| c.id).collect())
}

/// Write `edits`, record them and re-pin exactly what they changed: the
/// definitions, `hosts.json` (the record and the backups) and any edited file
/// the lock pins whole.
fn finish_edits(
    home: &Home,
    hosts: &[Host],
    edits: &[(crate::mcp::servers::Source, Done)],
    dry_run: bool,
    wrapping: bool,
    out: &mut Deferred,
) -> Result<usize> {
    if edits.is_empty() {
        return Ok(0);
    }
    wrap::write(home, edits, dry_run)?;
    let verb = match (dry_run, wrapping) {
        (true, _) => "would wrap",
        (false, true) => "✔ wrapped",
        (false, false) => "✔ unwrapped",
    };
    for (_, done) in edits {
        writeln!(
            out,
            "{verb} {} in {}",
            Named(&done.server.name),
            done.server.file.display()
        )?;
    }
    if dry_run {
        return Ok(edits.len());
    }
    let done: Vec<Done> = edits.iter().map(|(_, d)| d.clone()).collect();
    wrap::record(home, &done, wrapping)?;
    if home.lock_path().is_file() {
        // Without this, the change to the pinned `hosts.json` is drift that
        // denies every tool call (`kernel-integrity`).
        let lock = Lock::load(&home.lock_path())?;
        let mut rewritten = vec![home.hosts_path()];
        rewritten.extend(
            edits
                .iter()
                .map(|(source, _)| source.path.clone())
                .filter(|path| lock.pins(path)),
        );
        integrity::unpin(home, &[], &rewritten)?;
        let ids: BTreeSet<String> = done.iter().map(|d| d.server.id.clone()).collect();
        mcp::accept_ids(home, hosts, &ids)?;
    }
    Ok(edits.len())
}

#[cfg(test)]
mod tests;