openmoat 0.29.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
//! The JSON-RPC relay inside `moat mcp proxy`, between an agent host and one
//! stdio MCP server: the MCP gateway (ADR-045).
//!
//! The stdio transport is one JSON-RPC message (or batch) per line. The relay
//! reads each line whole, checks it, and passes on only what it read, written
//! again as compact JSON: a server or host never receives bytes the relay did
//! not check, so no difference between its JSON reader and theirs (a `\r`
//! inside a line, a key given twice, a number written two ways) can carry a
//! message past it. What it cannot read is not passed on: the host gets a parse
//! error for its own line, a server's line is dropped.
//!
//! From the host ([`host`]):
//! - a `tools/call` of a tool the pins hold or never accepted is answered with
//!   error -32602 naming `moat mcp accept` (ADR-026, ADR-032), and so is every
//!   call while the server's tools are being read again after it said they
//!   changed;
//! - every `tools/call` the pins let through, and every `resources/read` and
//!   `prompts/get`, goes to the [`Gate`], which decides it on the policy and
//!   the hook's decision for it and records it; a call it refuses is answered
//!   with error -32001 and never reaches the server;
//! - a message that is not a JSON-RPC request, notification or response, a
//!   request with an id that is not a string or a number, and a request reusing
//!   the id of one the server has not answered yet are answered with -32600.
//!
//! From the server ([`server`]):
//! - a response must answer a request the host sent and the server has not
//!   answered; any other is dropped, so a server cannot slip the host a listing
//!   or a result nobody asked for;
//! - a result, or an error answer, goes to the [`Gate`] before the host sees
//!   it, which keeps the pieces of a tool call's answer for the cross-server
//!   flow check (ADR-058) and what it names as injected input (ADR-057); one
//!   it cannot keep reaches the host as OpenMoat's error;
//! - a response that lists tools (`result.tools`) leaves out the tools the pins
//!   hold, and one that lists prompts, resources or resource templates the
//!   entries they hold; the answer to `initialize` reaches the host without
//!   `instructions`, and with the accepted `serverInfo`, while the pins hold
//!   them (ADR-069); a `prompts/get` of a held prompt is refused as a held
//!   tool's call is;
//! - `notifications/tools/list_changed` has the relay read the tools again
//!   itself, so a changed tool is held even when the host never lists again
//!   (a call the relay forwarded before it read the notification reaches the
//!   server, as it would without the relay: the hold starts at the notification);
//! - each request it sends the host (`sampling/createMessage`,
//!   `elicitation/create`, …) is recorded, its text kept as untrusted content of
//!   the session the proxy serves, and a sampling request that asks for the
//!   session's context (`includeContext` other than `none`) is refused; the
//!   host's answer is passed on only to a request the server sent and the host
//!   has not answered yet (ADR-069).
//!
//! Both revisions of the protocol are spoken (ADR-114, [`modern`], [`input`]):
//! the 2025 `initialize` answer is checked as above, and under MCP 2026-07-28
//! the `server/discover` answer is pinned the same way and every result's
//! `_meta` `serverInfo` against the accepted identity (another one holds the
//! server: its calls are refused). Which applies is read from what passes,
//! never chosen once: a server that answers both is checked on each answer
//! the host gets. A result's `inputRequests` (2026-07-28's way for a server to
//! ask for sampling, elicitation or roots) go through the same checks as the
//! server's own requests: sampling is refused unless the policy allows it, and
//! a URL-mode elicitation must send the person to an `https` page on a host the
//! policy does not deny. A tool whose schema breaks the `x-mcp-header` rules,
//! or whose `$ref`s leave it, loop or run too deep, is left out and its calls
//! refused (`tools/schema.rs`).

use std::collections::{BTreeMap, HashSet};
use std::sync::{Mutex, MutexGuard, PoisonError};

use anyhow::Result;
use serde_json::{Value, json};

use super::tools::ToolPins;

mod frame;
mod host;
mod input;
mod modern;
mod server;
mod surface;

pub use frame::{pump_host, pump_server, refuse_all};

/// JSON-RPC "invalid params", which MCP uses for an unknown tool.
const UNKNOWN_TOOL: i64 = -32602;
/// A JSON-RPC server error: OpenMoat refused the call.
const REFUSED: i64 = -32001;
/// JSON-RPC "invalid request".
const INVALID_REQUEST: i64 = -32600;
/// JSON-RPC "parse error".
const PARSE_ERROR: i64 = -32700;
/// The most requests to the host the server may leave unanswered at once.
const MAX_ASKED: usize = 4096;

/// What an MCP message asks the server to do, for the [`Gate`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
    /// `tools/call`: run a tool.
    Tool,
    /// `resources/read`: read a resource.
    Resource,
    /// `prompts/get`: fill in a prompt.
    Prompt,
}

/// One call the relay is about to pass on.
#[derive(Debug, Clone, Copy)]
pub struct Call<'a> {
    pub method: Method,
    /// The tool's or the prompt's name, or the resource's URI.
    pub name: &'a str,
    /// The tool's or prompt's arguments; `None` when the message has none.
    pub arguments: Option<&'a Value>,
    /// The client's request metadata, before forwarding to the server.
    pub metadata: Option<&'a Value>,
    /// The request's id as the relay matches its response ([`id_key`]);
    /// `None` for a notification, which gets no response.
    pub request: Option<&'a str>,
}

/// Decides and records what the relay passes on (`commands/mcp/gate.rs`).
pub trait Gate: Send + Sync {
    /// Decide and record `call`. `held` is why the pins refuse it, if they do:
    /// it is refused then whatever else holds, and still recorded. `Ok(Some)`
    /// is why it is refused; an error refuses it too.
    fn check(&self, call: &Call<'_>, held: Option<&str>) -> Result<Option<String>>;
    /// Record a request the server sent the host, with its `params`, whose
    /// text the host puts before the model or the person (a sampling
    /// request's messages, an elicitation's message); an error has it
    /// answered with an error instead of reaching the host.
    fn server_request(&self, method: &str, params: Option<&Value>) -> Result<()>;
    /// Record that the relay refused the server's `method` request, and why.
    fn server_refused(&self, method: &str, why: &str) -> Result<()> {
        let _ = (method, why);
        Ok(())
    }
    /// The server's answer to the host's request `request` ([`id_key`]), its
    /// `result` or its `error` object, before it reaches the host: the gate
    /// keeps what a tool call it passed returned (ADR-058, ADR-057), an error's
    /// `message` and `data` as much as a result. An error has the host answered
    /// with OpenMoat's error instead, so an answer is never seen by the model
    /// unrecorded.
    fn result(&self, request: &str, result: &Value) -> Result<()> {
        let _ = (request, result);
        Ok(())
    }
    /// The `instructions` of the server's `initialize` answer, which the
    /// host is passed (they match the pins): the gate keeps them as untrusted
    /// content for each session it serves (ADR-069).
    fn instructions(&self, text: &str) {
        let _ = text;
    }
    /// Why the policy refuses to have the person sent to `url`, the page of
    /// a URL-mode elicitation, if it does (ADR-114). The relay has already
    /// refused one that is not `https` or names a local address.
    fn url_refusal(&self, url: &str) -> Result<Option<String>> {
        let _ = url;
        Ok(None)
    }
}

/// Saves the pins after a listing changed them.
pub type Save = Box<dyn Fn(&ToolPins) -> Result<()> + Send + Sync>;

pub struct Relay {
    server: String,
    /// The policy's `mcp.allow_sampling`: sampling requests reach the host.
    allow_sampling: bool,
    state: Mutex<State>,
    gate: Box<dyn Gate>,
    save: Save,
    now_ms: fn() -> i64,
}

struct State {
    pins: ToolPins,
    /// No pins existed when the session started, the policy trusts first
    /// sight, and no listing came yet: the first listing is pinned as it is.
    first: bool,
    /// No pins existed when the session started and the policy trusts first
    /// sight: each part of the server's surface is pinned as first read.
    trust_unseen: bool,
    /// The id ([`id_key`]) of the host's `initialize` request the server has
    /// not answered yet.
    initialize: Option<String>,
    /// Why the pins could not be saved; every call is refused then.
    broken: Option<String>,
    /// The ids ([`id_key`]) of the host's requests the server has not
    /// answered yet.
    pending: HashSet<String>,
    /// The ids ([`id_key`]) of the server's requests the host has not
    /// answered yet: a host answer to any other is dropped.
    asked: HashSet<String>,
    /// The listing the relay asked for after the server said its tools changed.
    relist: Option<server::Relist>,
    /// How many listings the relay has asked for, for their ids.
    relists: u64,
    /// The ids ([`id_key`]) of the host's `server/discover` requests the
    /// server has not answered yet (MCP 2026-07-28).
    discovers: HashSet<String>,
    /// Which revisions of MCP the host spoke.
    spoken: Spoken,
    /// The `serverInfo` the server's first result named in this process.
    identity_seen: Option<Value>,
    /// Why the server's calls are refused for the rest of this process: a
    /// result named another `serverInfo` than the first.
    identity_changed: Option<String>,
    /// Tools listed with a schema OpenMoat refuses, with why (ADR-114).
    rejected: BTreeMap<String, String>,
}

/// Which revisions of MCP the host spoke (ADR-114).
#[derive(Default)]
struct Spoken {
    /// MCP 2026-07-28: a request's `_meta` named its protocol version.
    modern: bool,
    /// An earlier revision: the host sent `initialize`.
    legacy: bool,
    /// The 2026-07-28 protocol version the host's last request named, which
    /// the relay's own requests carry.
    protocol: Option<Value>,
}

/// Where a line goes.
#[derive(Debug, PartialEq, Eq)]
pub enum Routed {
    /// To the server.
    Server(String),
    /// To the host.
    Host(String),
    /// Nowhere: why the relay dropped what it read, for its standard error.
    Dropped(String),
}

impl Relay {
    /// `pins` as loaded; `None` for a server never seen. A server never seen
    /// has every tool held until a person accepts it (ADR-032), unless
    /// `trust_first_sight` (the policy's `mcp.trust_first_sight`) pins its
    /// first listing as it is.
    pub fn new(
        server: &str,
        pins: Option<ToolPins>,
        trust_first_sight: bool,
        gate: Box<dyn Gate>,
        save: Save,
        now_ms: fn() -> i64,
    ) -> Self {
        let first = pins.is_none() && trust_first_sight;
        Self {
            server: server.to_owned(),
            state: Mutex::new(State {
                pins: pins.unwrap_or_else(|| ToolPins::new(server)),
                first,
                trust_unseen: first,
                initialize: None,
                broken: None,
                pending: HashSet::new(),
                asked: HashSet::new(),
                relist: None,
                relists: 0,
                discovers: HashSet::new(),
                spoken: Spoken::default(),
                identity_seen: None,
                identity_changed: None,
                rejected: BTreeMap::new(),
            }),
            allow_sampling: false,
            gate,
            save,
            now_ms,
        }
    }

    /// Pass the server's sampling requests to the host (the policy's
    /// `mcp.allow_sampling`); refused by default (ADR-114).
    #[must_use]
    pub fn allowing_sampling(mut self, allow: bool) -> Self {
        self.allow_sampling = allow;
        self
    }

    fn state(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// One line from the host.
    pub fn host_line(&self, line: &str) -> Vec<Routed> {
        let Some(message) = read(line) else {
            if line.trim().is_empty() {
                return Vec::new();
            }
            // A line the relay cannot read is not passed on: a server's own
            // parser may read it (a lone surrogate, an out-of-range number),
            // and a `tools/call` in it would reach the server unchecked.
            let why = "OpenMoat's MCP proxy cannot read this message, so it is not passed on";
            return vec![Routed::Host(written(&error(
                &Value::Null,
                PARSE_ERROR,
                why,
            )))];
        };
        let Value::Array(batch) = message else {
            return match self.on_host(message) {
                host::Outcome::Forward(m) => vec![Routed::Server(written(&m))],
                host::Outcome::Reply(r) => vec![Routed::Host(written(&r))],
                host::Outcome::Drop => Vec::new(),
                host::Outcome::Dropped(why) => vec![Routed::Dropped(why)],
            };
        };
        if batch.is_empty() {
            let reply = error(
                &Value::Null,
                INVALID_REQUEST,
                "an empty batch is not a request",
            );
            return vec![Routed::Host(written(&reply))];
        }
        let (mut forward, mut replies, mut dropped) = (Vec::new(), Vec::new(), Vec::new());
        for message in batch {
            match self.on_host(message) {
                host::Outcome::Forward(m) => forward.push(m),
                host::Outcome::Reply(r) => replies.push(r),
                host::Outcome::Drop => {}
                host::Outcome::Dropped(why) => dropped.push(Routed::Dropped(why)),
            }
        }
        let mut out = Vec::new();
        if !forward.is_empty() {
            out.push(Routed::Server(written(&Value::Array(forward))));
        }
        if !replies.is_empty() {
            out.push(Routed::Host(written(&Value::Array(replies))));
        }
        out.extend(dropped);
        out
    }

    /// One line from the server.
    pub fn server_line(&self, line: &str) -> Vec<Routed> {
        let Some(message) = read(line) else {
            if line.trim().is_empty() {
                return Vec::new();
            }
            // The host's reader may take what this one refuses (a lone
            // surrogate, `NaN`): passed on, an unfiltered listing would reach it.
            return vec![Routed::Dropped(
                "a line from the server that is not JSON OpenMoat reads".to_owned(),
            )];
        };
        let Value::Array(batch) = message else {
            let mut out = Vec::new();
            if let Some(m) = self.on_server(message, &mut out) {
                out.push(Routed::Host(written(&m)));
            }
            return out;
        };
        let mut out = Vec::new();
        let forward: Vec<Value> = batch
            .into_iter()
            .filter_map(|m| self.on_server(m, &mut out))
            .collect();
        if !forward.is_empty() {
            out.push(Routed::Host(written(&Value::Array(forward))));
        }
        out
    }
}

/// `line` as one JSON value, or `None`.
fn read(line: &str) -> Option<Value> {
    serde_json::from_str::<Value>(line).ok()
}

/// `value` as the one line the relay sends: compact JSON, with U+0085,
/// U+2028 and U+2029 escaped as well as the control characters JSON escapes,
/// so no reader that splits lines on any of them (Python's `splitlines`)
/// sees two messages where the relay checked one.
pub(super) fn written(value: &Value) -> String {
    let mut out = Vec::new();
    let mut writer = serde_json::Serializer::with_formatter(&mut out, LineFormatter);
    match serde::Serialize::serialize(value, &mut writer) {
        Ok(()) => String::from_utf8(out).unwrap_or_else(|_| value.to_string()),
        Err(_) => value.to_string(),
    }
}

/// `serde_json`'s compact form, escaping the line breaks JSON leaves raw.
struct LineFormatter;

impl serde_json::ser::Formatter for LineFormatter {
    fn write_string_fragment<W: ?Sized + std::io::Write>(
        &mut self,
        writer: &mut W,
        fragment: &str,
    ) -> std::io::Result<()> {
        let mut rest = fragment;
        while let Some(at) = rest.find(['\u{85}', '\u{2028}', '\u{2029}']) {
            writer.write_all(&rest.as_bytes()[..at])?;
            let Some(c) = rest[at..].chars().next() else {
                break;
            };
            write!(writer, "\\u{:04x}", u32::from(c))?;
            rest = &rest[at + c.len_utf8()..];
        }
        writer.write_all(rest.as_bytes())
    }
}

/// A JSON-RPC request id as the relay matches responses to it: the exact
/// value, so `2` and `"2"` are two ids.
fn id_key(id: &Value) -> String {
    id.to_string()
}

fn error(id: &Value, code: i64, message: &str) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}

#[cfg(test)]
mod tests;