DEV Community

Gencay
Gencay

Posted on

Building a stdio policy proxy for local MCP servers in Rust

Once I started giving coding agents like Claude Code, Claude Desktop, and Cursor local filesystem and git MCP servers, I wanted one consistent rule set across all of them: fixed folder limits, tool allowlists, secret masking on tool output, and a local log of what ran. Spinning up a container for every small stdio server was too heavy for daily local work, so I wrote mcp-moat (CLI binary: moat), a Rust stdio proxy that sits between client and server.

Repo: https://github.com/gencay-e/mcp-moat

MCP client (Claude Code / Desktop / Cursor)
   |
   |  stdin / stdout (JSON-RPC)
   v
  moat  <--->  /dev/tty or CONIN$ (optional interactive prompt)
   |
   |  filtered JSON-RPC + scrubbed env
   v
local MCP server (filesystem, git, sqlite, ...)
Enter fullscreen mode Exit fullscreen mode

Prompting without touching stdout

Because JSON-RPC messages flow over stdin and stdout, printing an approval question to standard streams would corrupt the protocol frames. Instead, moat opens the controlling terminal directly:

impl DirectConsole {
    pub fn open() -> io::Result<Self> {
        #[cfg(windows)]
        {
            let in_file = OpenOptions::new().read(true).write(false).open("CONIN$")?;
            let out_file = OpenOptions::new().read(false).write(true).open("CONOUT$")?;
            Ok(Self {
                reader: Some(Box::new(BufReader::new(in_file))),
                writer: Some(Box::new(out_file)),
            })
        }

        #[cfg(not(windows))]
        {
            let tty_in = OpenOptions::new().read(true).write(false).open("/dev/tty")?;
            let tty_out = OpenOptions::new().read(false).write(true).open("/dev/tty")?;
            Ok(Self {
                reader: Some(Box::new(BufReader::new(tty_in))),
                writer: Some(Box::new(tty_out)),
            })
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

If there is no terminal attached, open() fails, and GUI clients like Claude Desktop and Cursor do not attach one at all. Passing --no-prompt disables DirectConsole so any unapproved call fails closed.

Counting hardlinks on two platforms

Symlink canonicalization alone misses hardlinked aliases: a file inside an allowed folder can still share an inode with a file outside it. moat inspects the link count cross-platform and denies files with nlink > 1:

#[cfg(unix)]
fn hardlink_count(path: &Path) -> Result<u64> {
    use std::os::unix::fs::MetadataExt;
    Ok(std::fs::metadata(path)?.nlink())
}

#[cfg(windows)]
fn hardlink_count(path: &Path) -> Result<u64> {
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
    };

    let file = std::fs::File::open(path)?;
    let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    // The File owns the handle for the full duration of this call.
    let succeeded = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) };
    if succeeded == 0 {
        return Err(std::io::Error::last_os_error().into());
    }
    Ok(u64::from(information.nNumberOfLinks))
}
Enter fullscreen mode Exit fullscreen mode

This runs on every existing file component as well as the canonical target, because a symlink inside the allowed folder could point at a hardlinked file. If the OS cannot report a link count, the ? propagates the error and blocks the call.

Walking paths that do not exist yet

Calling std::fs::canonicalize fails when an agent wants to create a/b/new.txt and a does not exist yet. To handle new destinations safely, moat walks the path component by component with std::fs::symlink_metadata:

for (index, component) in components.iter().enumerate() {
    match component {
        Component::Prefix(p) => verified_prefix.push(p.as_os_str()),
        Component::RootDir => verified_prefix.push(Component::RootDir.as_os_str()),
        Component::Normal(segment) => {
            if missing_started {
                missing_segments.push(segment.to_os_string());
                continue;
            }
            verified_prefix.push(segment);
            match std::fs::symlink_metadata(&verified_prefix) {
                Ok(meta) => {
                    // Symlinks/junctions are resolved and checked against allowed_paths;
                    // regular files run through hardlink_count(&verified_prefix).
                }
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    missing_started = true;
                    missing_segments.push(segment.to_os_string());
                }
                Err(err) => return Err(err.into()),
            }
        }
        _ => {}
    }
}
Enter fullscreen mode Exit fullscreen mode

Once the first missing directory appears, verified_prefix holds the deepest existing ancestor inside allowed_paths, and missing_segments goes through lexical validation.

moat does not try to normalize ..; it rejects it on the raw string and again after up to four rounds of percent-decoding, so %2e%2e/ and %252e%252e fail too. Incoming file:// URIs in tools/call arguments and in resources/read or resources/subscribe are converted to local paths via parse_file_uri_to_path and go through the same path jail.

Env scrubbing, presets, masking, and audit logs

Before spawning the MCP server, moat strips sensitive environment variables (scrub_env enabled by default) and enforces tool allowlists or built-in presets (filesystem, git, fetch, sqlite, memory, postgres, playwright). Writes targeting .env files or SSH keys inside an allowed directory require confirmation, and regex-based DLP masks common secret formats in stdout and stderr.

Audit logging is opt-in via --audit-log and writes a hash-chained JSONL log with a closing session_end seal (moat audit verify --require-seal). If MOAT_AUDIT_KEY is set, entries are authenticated with HMAC-SHA256 while keeping MOAT_AUDIT_KEY stripped from the child server environment.

Quick check

Install from crates.io (or download prebuilt binaries for Linux, macOS, and Windows from GitHub Releases):

cargo install --locked mcp-moat
moat wrap --preset filesystem --no-prompt -- npx -y @modelcontextprotocol/server-filesystem .
Enter fullscreen mode Exit fullscreen mode

Threat model and limits

  • It is not an OS sandbox. This is a userspace JSON-RPC policy proxy meant for a misbehaving or prompt-injected client talking to a local server you trust, not bwrap, sandbox-exec, or a VM.
  • TOCTOU races between the proxy check and the server opening the file are still possible.
  • Secret masking relies on regex patterns, so unknown formats, base64-encoded payloads, or secrets split across messages pass through.
  • Rejecting every file with nlink > 1 also blocks harmless hardlinks, such as pnpm's content-addressable store or the objects of a repo cloned from a local path.
  • It only speaks stdio, with no HTTP or SSE transport.

Unit tests and a 1,840-case policy matrix run in CI across Linux, macOS, and Windows, and scripts/real_server_check.py exercises eight real MCP servers on Linux (filesystem, git, everything, memory, sqlite, fetch, postgres, and playwright). Licensed under MIT.

Source: https://github.com/gencay-e/mcp-moat

Top comments (0)