openmoat 0.9.0

Policy checks for AI coding agents: decides allow, defer, ask or deny for every tool call from Claude Code, Codex and Cursor, configures Claude Code's and Codex'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
//! Where each agent host reads its MCP server definitions, and reading them.
//!
//! - Claude Code: `~/.claude.json` (`$CLAUDE_CONFIG_DIR/.claude.json` when that is
//!   set) with `mcpServers` for the user and `projects.<path>.mcpServers` for each
//!   project's local servers, and a project's `.mcp.json`.
//! - Codex: `config.toml` beside its hook file (`[mcp_servers.<name>]`), and a
//!   project's `.codex/config.toml`.
//! - Cursor: `mcp.json` beside its hook file, and a project's `.cursor/mcp.json`.
//! - OpenClaw: `mcp.servers.<name>` in `openclaw.json` (JSON5), wherever
//!   `OPENCLAW_CONFIG_PATH` or the state directory puts it
//!   (<https://docs.openclaw.ai/tools/mcp>, "Server definitions live under
//!   `mcp.servers`"). The lock pins the rest of that file whole
//!   (`integrity/digest.rs`). Plugin bundles bring their own `.mcp.json`; they
//!   are plugin code, which `runs-later` asks before an agent writes.
//! - GitHub Copilot CLI: `mcp-config.json` in its configuration directory, and a
//!   project's `.mcp.json` and `.github/mcp.json`, wrapped in `mcpServers` or bare.
//! - pi: `mcp.json` in its agent directory, and a project's `.pi/mcp.json`.
//! - Gemini CLI: `mcpServers` in its `settings.json`, the user's and a project's.
//!
//! Project files are looked for in the working directory and each directory above
//! it up to the project root. A file that does not exist lists no servers.

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context as _, Result};
use openmoat_hosts::{Host, McpFile};
use serde_json::{Map, Value};
use toml_edit::{DocumentMut, Item};

use crate::home::{Home, user_home};
use crate::install::HostConfig;

/// How a file lays out its servers.
pub use openmoat_hosts::McpLayout as Layout;

/// A file one host reads MCP servers from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
    pub host: Host,
    pub path: PathBuf,
    pub layout: Layout,
    /// A user-level file (in the host's configuration), not a project's.
    pub user: bool,
}

/// One server definition as its host reads it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Server {
    /// `<file>#<pointer>`, the lock's key for this definition.
    pub id: String,
    pub host: Host,
    pub file: PathBuf,
    /// The JSON pointer of the entry inside the file (`/mcpServers/github`).
    pub pointer: String,
    pub name: String,
    pub entry: Value,
}

/// What reading a set of sources found.
#[derive(Debug, Default)]
pub struct Scan {
    pub servers: Vec<Server>,
    /// Files that exist but could not be read or parsed, with the reason.
    pub unreadable: Vec<(PathBuf, String)>,
    /// Every file looked at, present or not, so a pin from one of them whose
    /// entry is gone counts as removed.
    pub scanned: Vec<PathBuf>,
}

/// The files `host` reads servers from, for a session in `cwd` (none of a
/// project's when `cwd` is `None` or in no project).
pub fn sources(home: &Home, host: Host, cwd: Option<&Path>) -> Result<Vec<Source>> {
    let Some(mcp) = &host.spec().mcp else {
        return Ok(Vec::new());
    };
    let mut out: Vec<Source> = user_files(home, host, mcp.user_file)?
        .into_iter()
        .map(|path| Source {
            host,
            path,
            layout: mcp.user_layout,
            user: true,
        })
        .collect();
    if let Some(cwd) = cwd
        && !mcp.project_files.is_empty()
    {
        for dir in project_dirs(cwd)? {
            for (relative, layout) in mcp.project_files {
                out.push(Source {
                    host,
                    path: dir.join(relative),
                    layout: *layout,
                    user: false,
                });
            }
        }
    }
    Ok(out)
}

/// Where `file`, `host`'s user-level MCP server file, can be. Claude Code reads
/// `.claude.json` from the home directory unless `CLAUDE_CONFIG_DIR` is set, and
/// from inside that directory when it is, even when it names the default
/// `~/.claude`. A moved directory is always named by the variable; for the
/// default one the environment `moat` runs in need not be the agent's, so both
/// files are read.
fn user_files(home: &Home, host: Host, file: McpFile) -> Result<Vec<PathBuf>> {
    let config = HostConfig::for_host(home, host)?;
    Ok(match file {
        McpFile::HookFile => vec![config.settings_path],
        McpFile::BesideHookFile(name) => vec![config.settings_path.with_file_name(name)],
        McpFile::InConfigDir(name) => vec![config.dir().join(name)],
        McpFile::BesideDefaultDir(name) => {
            let user = user_home()?;
            let default = host.spec().install.as_ref().map(|i| user.join(i.dir_name));
            let inside = config.dir().join(name);
            if default.is_some_and(|d| config.dir() == d) {
                vec![user.join(name), inside]
            } else {
                vec![inside]
            }
        }
    })
}

/// `cwd` and each directory above it up to its project root; none outside a project.
/// The directory is taken with its links resolved: `openmoat init` gets it
/// from the operating system that way, a hook gets it as the agent spelt it
/// (`/var/…` and `/private/var/…` on macOS), and both must name the same
/// project file for its pins to be found.
fn project_dirs(cwd: &Path) -> Result<Vec<PathBuf>> {
    let (cwd, home) = (resolved(cwd), resolved(&user_home()?));
    let cwd = cwd.as_path();
    let Some(root) = crate::project::root_of(cwd, &home) else {
        return Ok(Vec::new());
    };
    Ok(cwd
        .ancestors()
        .take_while(|dir| dir.starts_with(&root))
        .map(Path::to_path_buf)
        .collect())
}

/// `path` with its links resolved on Unix; as given when it cannot be, and on
/// Windows, whose resolved form (`\\?\C:\…`) would differ from every other
/// spelling of the path OpenMoat records.
fn resolved(path: &Path) -> PathBuf {
    if cfg!(unix) {
        std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
    } else {
        path.to_path_buf()
    }
}

/// Read every server `sources` define.
pub fn scan(sources: &[Source]) -> Scan {
    let mut found = Scan::default();
    for source in sources {
        found.scanned.push(source.path.clone());
        let text = match fs::read_to_string(&source.path) {
            Ok(text) => text,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => {
                found.unreadable.push((source.path.clone(), e.to_string()));
                continue;
            }
        };
        match parse(source, &text) {
            Ok(servers) => found.servers.extend(servers),
            Err(e) => found
                .unreadable
                .push((source.path.clone(), format!("{e:#}"))),
        }
    }
    found
}

/// The servers `text`, the contents of `source`, defines.
pub fn parse(source: &Source, text: &str) -> Result<Vec<Server>> {
    let mut out = Vec::new();
    let mut add = |pointer: String, name: &str, entry: &Value| {
        out.push(Server {
            id: format!("{}#{pointer}", source.path.display()),
            host: source.host,
            file: source.path.clone(),
            pointer,
            name: name.to_owned(),
            entry: entry.clone(),
        });
    };
    match source.layout {
        Layout::Json | Layout::ClaudeJson => {
            if text.trim().is_empty() {
                return Ok(Vec::new());
            }
            let root: Value = serde_json::from_str(text).context("parsing JSON")?;
            for (name, entry) in servers_in(&root, "mcpServers") {
                add(format!("/mcpServers/{}", escape(name)), name, entry);
            }
            if source.layout == Layout::ClaudeJson
                && let Some(projects) = root.get("projects").and_then(Value::as_object)
            {
                for (project, settings) in projects {
                    for (name, entry) in servers_in(settings, "mcpServers") {
                        let pointer =
                            format!("/projects/{}/mcpServers/{}", escape(project), escape(name));
                        add(pointer, name, entry);
                    }
                }
            }
        }
        Layout::JsonOrBare => {
            if text.trim().is_empty() {
                return Ok(Vec::new());
            }
            let root: Value = serde_json::from_str(text).context("parsing JSON")?;
            for (name, entry) in servers_in(&root, "mcpServers") {
                add(format!("/mcpServers/{}", escape(name)), name, entry);
            }
            // Read whichever way the file is laid out: a top-level entry
            // that looks like a server is pinned too, so a bare file cannot
            // start a server OpenMoat did not see.
            for (name, entry) in root.as_object().into_iter().flatten() {
                if name != "mcpServers" && looks_like_server(entry) {
                    add(format!("/{}", escape(name)), name, entry);
                }
            }
        }
        Layout::Toml => {
            let doc: DocumentMut = text.parse().context("parsing TOML")?;
            if let Some(Value::Object(servers)) = doc.get("mcp_servers").map(toml_to_json) {
                for (name, entry) in &servers {
                    add(format!("/mcp_servers/{}", escape(name)), name, entry);
                }
            }
        }
        Layout::OpenClaw => {
            let root = crate::install::openclaw::parse(text)
                .context("parsing JSON5")?
                .value;
            refuse_include(&root)?;
            if let Some(servers) = root.pointer("/mcp/servers").and_then(Value::as_object) {
                for (name, entry) in servers {
                    add(format!("/mcp/servers/{}", escape(name)), name, entry);
                }
            }
        }
    }
    Ok(out)
}

/// OpenClaw merges in the files an `$include` key names; one where MCP
/// servers may come from hides which servers OpenClaw starts.
fn refuse_include(root: &Value) -> Result<()> {
    for at in ["", "/mcp", "/mcp/servers"] {
        if root
            .pointer(at)
            .and_then(Value::as_object)
            .is_some_and(|o| o.contains_key("$include"))
        {
            let place = if at.is_empty() { "the top level" } else { at };
            anyhow::bail!(
                "`$include` at {place} may bring MCP servers from another file, which OpenMoat \
                 does not read; move `mcp.servers` into this file"
            );
        }
    }
    Ok(())
}

/// An object naming how a server starts or is reached.
fn looks_like_server(entry: &Value) -> bool {
    ["command", "url", "type"]
        .iter()
        .any(|key| entry.get(key).is_some())
}

/// The `(name, entry)` pairs of the object at `key` in `value`.
fn servers_in<'a>(value: &'a Value, key: &str) -> impl Iterator<Item = (&'a String, &'a Value)> {
    value
        .get(key)
        .and_then(Value::as_object)
        .into_iter()
        .flat_map(Map::iter)
}

/// A JSON pointer token (RFC 6901): `~` and `/` escaped.
pub fn escape(token: &str) -> String {
    token.replace('~', "~0").replace('/', "~1")
}

/// A TOML item as JSON, so TOML and JSON definitions pin alike.
pub fn toml_to_json(item: &Item) -> Value {
    match item {
        Item::None => Value::Null,
        Item::Value(value) => toml_value(value),
        Item::Table(table) => Value::Object(
            table
                .iter()
                .map(|(k, v)| (k.to_owned(), toml_to_json(v)))
                .collect(),
        ),
        Item::ArrayOfTables(tables) => Value::Array(
            tables
                .iter()
                .map(|t| toml_to_json(&Item::Table(t.clone())))
                .collect(),
        ),
    }
}

fn toml_value(value: &toml_edit::Value) -> Value {
    use toml_edit::Value as T;
    match value {
        T::String(s) => Value::String(s.value().clone()),
        T::Integer(i) => Value::from(*i.value()),
        T::Float(f) => serde_json::Number::from_f64(*f.value())
            .map_or_else(|| Value::String(f.value().to_string()), Value::Number),
        T::Boolean(b) => Value::Bool(*b.value()),
        T::Datetime(d) => Value::String(d.value().to_string()),
        T::Array(items) => Value::Array(items.iter().map(toml_value).collect()),
        T::InlineTable(table) => Value::Object(
            table
                .iter()
                .map(|(k, v)| (k.to_owned(), toml_value(v)))
                .collect(),
        ),
    }
}

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

    fn source(layout: Layout) -> Source {
        Source {
            host: Host::ClaudeCode,
            path: PathBuf::from("/h/.claude.json"),
            layout,
            user: true,
        }
    }

    #[test]
    fn claude_json_lists_user_and_project_servers() {
        let text = r#"{"mcpServers": {"gh": {"command": "npx", "args": ["-y", "gh"]}},
            "projects": {"/p/a": {"mcpServers": {"db/x": {"command": "db"}}}, "/p/b": {}},
            "numStartups": 4}"#;
        let servers = parse(&source(Layout::ClaudeJson), text).unwrap();
        let ids: Vec<&str> = servers.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(
            ids,
            [
                "/h/.claude.json#/mcpServers/gh",
                "/h/.claude.json#/projects/~1p~1a/mcpServers/db~1x"
            ]
        );
        assert_eq!(servers[1].name, "db/x");
        assert_eq!(servers[0].entry["args"][1], "gh");
    }

    #[test]
    fn a_plain_json_file_has_no_project_servers() {
        let text = r#"{"mcpServers": {"a": {"url": "https://x"}}, "projects": {"/p": {"mcpServers": {"b": {}}}}}"#;
        let servers = parse(&source(Layout::Json), text).unwrap();
        assert_eq!(servers.len(), 1);
        assert!(parse(&source(Layout::Json), "  ").unwrap().is_empty());
        assert!(parse(&source(Layout::Json), "{").is_err());
    }

    #[test]
    fn codex_toml_servers_read_as_json() {
        let text = "model = \"x\"\n[mcp_servers.docs]\ncommand = \"docs-server\"\nargs = [\"--port\", \"4000\"]\nenv = { TOKEN = \"t\" }\nstartup_timeout_sec = 20\n";
        let servers = parse(&source(Layout::Toml), text).unwrap();
        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].pointer, "/mcp_servers/docs");
        assert_eq!(
            servers[0].entry,
            serde_json::json!({"command": "docs-server", "args": ["--port", "4000"],
                "env": {"TOKEN": "t"}, "startup_timeout_sec": 20})
        );
    }

    #[test]
    fn openclaw_servers_are_read_from_json5() {
        let openclaw = Source {
            host: Host::OpenClaw,
            path: PathBuf::from("/h/.openclaw/openclaw.json"),
            ..source(Layout::OpenClaw)
        };
        let text = "// mine\n{ mcp: { servers: { 'my/docs': { url: 'https://x/mcp', \
                    transport: 'streamable-http', }, }, }, gateway: { port: 1 } }";
        let servers = parse(&openclaw, text).unwrap();
        assert_eq!(servers.len(), 1);
        assert_eq!(
            servers[0].id,
            "/h/.openclaw/openclaw.json#/mcp/servers/my~1docs"
        );
        assert_eq!(servers[0].name, "my/docs");
        assert_eq!(servers[0].entry["transport"], "streamable-http");
        assert!(parse(&openclaw, "").unwrap().is_empty());
        assert!(parse(&openclaw, "{ gateway: {} }").unwrap().is_empty());
        for include in [
            r#"{"$include": "./more.json5"}"#,
            r#"{"mcp": {"servers": {"$include": ["./a.json5"]}}}"#,
        ] {
            let refused = parse(&openclaw, include).unwrap_err().to_string();
            assert!(refused.contains("$include"), "{refused}");
        }
        // An `$include` elsewhere cannot bring servers.
        assert!(parse(&openclaw, r#"{"agents": {"$include": "./a.json5"}}"#).is_ok());
    }

    #[test]
    fn copilot_project_files_are_read_wrapped_or_bare() {
        let copilot = Source {
            path: PathBuf::from("/p/.mcp.json"),
            ..source(Layout::JsonOrBare)
        };
        let wrapped = r#"{"mcpServers": {"gh": {"type": "local", "command": "npx"}}}"#;
        let bare = r#"{"gh": {"type": "local", "command": "npx"}, "web": {"url": "https://x"},
            "note": "not a server", "empty": {}}"#;
        let ids = |text| -> Vec<String> {
            parse(&copilot, text)
                .unwrap()
                .into_iter()
                .map(|s| s.id)
                .collect()
        };
        assert_eq!(ids(wrapped), ["/p/.mcp.json#/mcpServers/gh"]);
        assert_eq!(ids(bare), ["/p/.mcp.json#/gh", "/p/.mcp.json#/web"]);
        assert!(parse(&copilot, "").unwrap().is_empty());
        assert!(parse(&copilot, "[").is_err());
    }

    #[test]
    fn scan_skips_missing_files_and_reports_broken_ones() {
        let dir = tempfile::tempdir().unwrap();
        let broken = dir.path().join("mcp.json");
        fs::write(&broken, "{not json").unwrap();
        let missing = dir.path().join("absent.json");
        let sources: Vec<Source> = [&broken, &missing]
            .into_iter()
            .map(|p| Source {
                path: p.clone(),
                ..source(Layout::Json)
            })
            .collect();
        let found = scan(&sources);
        assert!(found.servers.is_empty());
        assert_eq!(found.scanned.len(), 2);
        assert_eq!(found.unreadable.len(), 1);
        assert_eq!(found.unreadable[0].0, broken);
    }
}