mcp-moat
mcp-moat (moat)
A policy proxy for MCP servers, written in Rust. moat sits between an MCP client (for example Claude Desktop, Claude Code, Cursor) and an MCP server that talks JSON-RPC over stdio. It checks tool calls against a policy, masks secrets in server output, can ask the operator before sensitive actions, and can reduce the size of tool schemas and outputs.
moat filters stdio traffic and prompts the operator, but it does not sandbox the server process itself. Read SECURITY.md for what it does not protect against, and CHANGELOG.md for the current release (0.3.0).
What it does
A real run of moat in front of @modelcontextprotocol/server-filesystem, allowed folder /srv/demo/project. The verdict lines are shortened from moat's responses; scripts/demo.py drives the run and checks each line against the real output. The scripted MCP client read notes.md (which holds a key), tried to read ../.ssh/id_ed25519 outside the folder, and tried to write project/.env, which was denied because --no-prompt is set:
$ moat audit query audit.jsonl --violations-only
#4 [Outbound] method=dlp_redaction -> - [DLP: 4 redacted]
#5 [Inbound] method=tools/call tool=read_file -> BLOCK (Path outside boundary: path '/srv/demo/.ssh/id_ed25519' is not within allowed root '/srv/demo/project')
#6 [Inbound] method=tools/call tool=write_file target=/srv/demo/project/.env -> ASK_OPERATOR [Operator: Deny] (Attempted modification of protected configuration/hook: /srv/demo/project/.env)
$ moat audit verify audit.jsonl
[moat] Audit Log Integrity Check: PASSED
Path: audit.jsonl
Verified Records: 6
Cryptographic Chain: INTACT (SHA-256)The output is from a run of scripts/demo.py and is shortened (timestamps and empty columns removed, the temporary folder replaced by /srv/demo). The scripted MCP client got OPENAI_API_KEY=[MCP-MOAT-REDACTED-SECRET] instead of the key.
Policy checks
Path jail. File paths in tool calls must stay inside the directories given with
--allow(orallowed_pathsinmoat.toml). Paths with.., percent-encoded or double-encoded traversal, andfile://URIs forresources/readandresources/subscribeare checked the same way. The jail is checked first: a call with a path outside the jail is blocked whatever the tool name or the other arguments are, also when it carries a command.UNC and NT paths. Paths starting with
\\,//,\??\,/??/,\device\or/device/are rejected before any file system access, as are the\GLOBAL??\,\GLOBALROOT\,\DosDevices\,\SystemRoot\,\BaseNamedObjects\,\ArcName\and\KernelObjects\namespaces. Separators are normalized first, so mixed forms such as\/?\C:\are caught too. This is a text check. It has not been verified against a real SMB or NTLM scenario on Windows.Protected files. Writes to files such as
.git,.gitmodules,.gitconfig,.env,moat.toml,.vscode,.github, the audit log, SSH keys and AWS credentials always need operator approval. The file passed to--configis added to this list automatically, so an agent cannot rewrite the policy that guards it.Read-only mode.
--read-onlyblocks tools that look like they modify files, based on tool name prefixes and suffixes, and tools listed incustom_modifying_tools.Blocked commands.
blocked_commandsandblocked_commands_regexreject shell commands. Literal rules are tokenized: whitespace is collapsed, path prefixes such as/bin/rmare resolved to the program name, and combined short flags are compared as sets.rm -rf /,rm -r -f /,/bin/rm -fr /andsudo rm -rf /are blocked, whilerm -rf /tmp/buildgoes to the operator prompt. This is not a complete shell parser, see SECURITY.md.Shell metacharacters. Command arguments with
|,&,;,$, backticks,<,>or control characters are not blocked outright. They need operator approval. PowerShell encoded-command flags are blocked.Reserved device names. Path segments such as
CON,NUL,AUX,COM1are rejected on all platforms. On Linux and macOS this also rejects real directories with these names.Symlinks and hardlinks. Paths are resolved and checked against the jail. Hardlink checks (link count above 1) exist on Unix only. Symlinks to the outside are tested on Linux by
scripts/real_server_check.py, not on macOS or Windows. A change between the check and the use of a file cannot be ruled out.Batch requests. JSON-RPC batch arrays are rejected.
Secret masking
Output from the server (stdout and stderr) is scanned and known secret formats are replaced with [MCP-MOAT-REDACTED-SECRET]. Covered formats include OpenAI keys (including sk-proj-, sk-svcacct- and sk-admin-), Anthropic, DeepSeek, Mistral (with mistral context), Perplexity, Voyage AI, Cohere, Google AI Studio keys, GitHub tokens, GitLab tokens, Slack tokens, Stripe keys, npm and PyPI tokens, Hugging Face tokens, AWS access keys and temporary session keys (ASIA...), AWS secret access keys next to aws or secret, bearer tokens and PEM private key blocks. Unicode-escaped variants (\u0073\u006b-...) are decoded before matching.
dlp_base64_heuristic = true in moat.toml also masks long Base64 and Base64url runs with upper case, lower case and digits. It is off by default because it also masks image and audio data, file paths, lockfile hashes, long identifiers and public keys, which breaks those responses.
Not covered: secrets in other formats, Base64-encoded secrets (unless the heuristic is on), and secrets split across several messages.
Operator prompts
For actions that need approval, moat asks on the terminal device directly (/dev/tty on Unix, CONIN$ on Windows), so the JSON-RPC stream on stdin and stdout is not disturbed. File changes are shown as a diff. [a]llow always remembers the decision for the session. For shell tools the decision is remembered per exact action only. With --no-prompt, every action that needs approval is denied, and the block message says that --no-prompt is the reason.
Stream handling
Lines longer than 16 MB are dropped and answered with a JSON-RPC error.
stderrof the child process is drained in its own task, so the child cannot block on a full pipe.pingrequests are passed on with priority.On Ctrl+C the child process is terminated and
moatexits with code 130.--monitor(alias--audit-only) does not block. It forwards everything and logs what would have been blocked. The terminal diagnostic names the tool and a fixed category (for example "path outside allowed folder"), never the path from the request.
Audit log
--audit-log <file> writes one JSON line per event. Each line contains the SHA-256 hash of the previous line (prev_hash). moat audit verify <file> checks the chain and reports the first broken line.
What this detects: changing, reordering or deleting a line in the middle of a session.
What this does not detect: cutting lines off the end, deleting a whole session, deleting the file, or rebuilding a log from scratch. The hash is not keyed and there is no external anchor. Do not treat the log as tamper-proof evidence. Previews in the log are passed through the secret masking.
If the audit log cannot be written, the call is not forwarded (fail closed).
Other commands: moat audit query <file> --violations-only, moat audit query <file> --tool <name>, moat audit tail <file> -f.
Schema and output reduction (--compact-schemas, --max-output-bytes, --hide-tool)
--compact-schemasremoves metadata such as$schema,title,examplesand long descriptions fromtools/listresponses. With--read-only, tools that modify files are removed from the list.--max-output-bytes <N>cuts text output of a tool or resource to N bytes and adds a marker.--hide-tool <name>removes a tool fromtools/listand blocks calls to it.
How much this saves depends on the server. No fixed percentage is claimed.
Code generation (moat codegen)
Reads tools/list from a running server or from a JSON file, applies the policy (hidden tools, read-only), and writes TypeScript declarations (--format ts), Python stubs (--format python) or a Markdown table (--format compact-md).
Related MCP server: ShadowRun
Install
cargo install --locked mcp-moatFrom a release
Download the archive for your system and
SHA256SUMSfrom the Releases page.Check the hash.
Linux:
sha256sum -c SHA256SUMS --ignore-missingmacOS:
shasum -a 256 -c SHA256SUMS --ignore-missingWindows (PowerShell): compare the output of
Get-FileHash .\moat-windows-x86_64.zip -Algorithm SHA256with the line in
SHA256SUMS.Unpack the archive and put
moat(moat.exe) on yourPATH.
Archives are built for Linux x86_64, macOS aarch64, macOS x86_64 and Windows x86_64. They are not signed.
From source
cargo build --release --locked --bin moatThe binary is target/release/moat (moat.exe on Windows).
Usage
Create a commented moat.toml in the current directory:
moat initWrap an MCP server. Everything after -- is the server command.
# Filesystem server, limited to the current directory
moat wrap --preset filesystem -- npx -y @modelcontextprotocol/server-filesystem .
# Git server
moat wrap --preset git -- python -m mcp_server_git
# Read-only
moat wrap --preset filesystem --read-only -- npx -y @modelcontextprotocol/server-filesystem .
# No prompts: deny everything that needs approval (for CI)
moat wrap --preset filesystem --no-prompt -- npx -y @modelcontextprotocol/server-filesystem .
# With audit log
moat wrap --preset filesystem --audit-log .moat/audit.jsonl --audit-level full -- npx -y @modelcontextprotocol/server-filesystem .Presets: filesystem, git, fetch, sqlite, memory.
Configuration (moat.toml)
moat reads moat.toml from the current directory, or the file given with --config.
# Allowed root paths for filesystem access.
allowed_paths = ["."]
# Block all tools that look like they modify files.
read_only = false
# Require operator approval for writes inside allowed directories.
# Protected files always require approval.
require_approval_on_write = false
# Shell command patterns that are blocked (tokenized match).
blocked_commands = [
"rm -rf /",
":(){ :|:& };:",
"mkfs",
"dd if=/dev/zero",
"format c:",
"powershell -enc",
]
# Tools that never need approval. A tool that moat does not know is blocked until it is listed
# here (or covered by a preset). custom_modifying_tools only classifies a tool, it does not allow it.
always_allow_tools = [
"list_directory",
"read_file",
"search_files",
"grep",
]
# Tools with a file-like name (get_*, read_*, ...) that take no path, for example "get-sum".
# Otherwise they are blocked, because moat finds no path to check.
# non_file_tools = ["get-sum"]
# Argument names that look like paths but are not. Ignored for every tool. The git and memory
# presets ignore their keys for their own tools only.
# ignore_path_keys = ["target"]
compact_schemas = false
# max_output_bytes = 16384
hidden_tools = []
# Extra JSON-RPC methods to forward (exact match). Only the standard MCP client-to-server
# methods are forwarded by default; any other method is refused (-32601).
# allowed_methods = ["x/vendor_method"]
# Mask long Base64 runs as possible secrets. Off by default, see "Secret masking".
# dlp_base64_heuristic = false
# Extra files that always require approval. The active --config file is added automatically.
# protected_files = ["important.txt"]Validate a configuration (moat check)
moat check parses the TOML, verifies that every allowed_paths entry exists and is a directory, checks the audit-log path, and compiles the blocked-command regexes. It does not start a server.
moat check
moat check --config ./configs/strict.tomlThe command prints Config OK: <source> and the resolved allowed roots. It exits non-zero with a specific error when a path or regex is invalid.
Shell completions (moat completion)
moat completion bash
moat completion zsh
moat completion fish
moat completion powershellPipe the output to your shell's completion directory, for example:
moat completion bash > ~/.local/share/bash-completion/completions/moatClaude Desktop
Edit claude_desktop_config.json (Windows: %APPDATA%\Claude\, macOS: ~/Library/Application Support/Claude/):
{
"mcpServers": {
"protected-filesystem": {
"command": "C:\\path\\to\\moat.exe",
"args": [
"wrap",
"--allow", "C:\\Projects\\MyProject",
"--",
"npx", "-y", "@modelcontextprotocol/server-filesystem", "C:\\Projects\\MyProject"
]
}
}
}Cursor
.cursor/mcp.json:
{
"mcpServers": {
"guarded-git": {
"command": "moat",
"args": ["wrap", "--allow", ".", "--read-only", "--", "mcp-server-git"]
}
}
}Tested against real MCP servers
scripts/real_server_check.py starts mcp-moat in front of three real servers and checks 58 cases (56 on Windows, where the two symlink cases are skipped). It needs Node.js, Python and git, and runs in CI on Linux.
@modelcontextprotocol/server-filesystem: reads inside and outside the jail,.., symlinks to the outside, protected files, read-only mode, secret masking, audit chain.mcp-server-git: this server does not restrict itself. It reads any repository you name. mcp-moat keeps it inside the allowed folder, including relative file lists such asfiles: ["src/main.rs"], which are checked againstrepo_path.@modelcontextprotocol/server-everything: a tool that dumps the environment (get-env) has its secrets masked; tools that are not on the allow list are blocked.
The servers are pinned: @modelcontextprotocol/server-filesystem@2.3.0, @modelcontextprotocol/server-everything@2.3.0 and mcp-server-git==2026.11.11 (also in scripts/demo.py and the CI workflow). Update the pins on purpose and run the check again. Other MCP servers and versions were not tested.
Good to know
Order of checks. (1) hidden tool, (2) path jail for every path argument, (3) file tool without a path, (4) modifying tool in read-only mode, (5) tool that is not authorized and does not modify, (6) blocked command, (7) any other command argument, (8) modifying tool with a protected file,
require_approval_on_write(also without a path) or no authorization. The first match wins; the full table is indocs/security-model.md. A path outside the jail is always a block, never a prompt.Authorization. A tool is allowed without the operator only if it is listed in
always_allow_toolsorcustom_always_allow_tools, is enabled by a preset, or has the exact name of a tool of@modelcontextprotocol/server-filesystem(read_file,read_text_file,read_media_file,read_multiple_files,write_file,edit_file,append_file,copy_file,create_directory,list_directory,list_directory_with_sizes,directory_tree,move_file,search_files,get_file_info,list_allowed_directories). A name that only looks like a file tool (read_*,write_*,get_*) or a look-alike (rm,cat,shred,delete_file) never authorizes a tool. An unlisted tool that modifies needs operator approval (denied with--no-prompt), any other unlisted tool is blocked. List the tool inalways_allow_toolsorcustom_always_allow_toolsto allow it.Classification is not authorization.
custom_modifying_toolsmarks a tool as modifying:--read-onlyblocks it and it counts as a write. It does not allow the tool. Add the tool toalways_allow_toolsas well if it should run without a prompt.Commands. A call with a command argument is never allowed automatically. It is blocked (blocked command) or needs operator approval. A tool that is not authorized and does not modify is blocked before its command is looked at.
Tools without a path. Tools with a file-like name that take no path (
get-sum) neednon_file_tools = ["get-sum"], otherwise mcp-moat blocks them because it finds no path to check. This includes calls without arguments.list_allowed_directoriesis exempt.non_file_toolsdoes not allow a tool; paths that are present are still checked. The presets list their own pathless tools (see below).URLs and paths. Only local paths and
file://URIs are checked as paths. Anhttp://orhttps://URL in a URL argument (url,uri,href,*_url) is not a path and is not jail-checked. The tool that fetches it must still be authorized (listed or enabled by a preset). Anhttp(s)URL in a path argument (path,file) is rejected, andfile://URLs and bare paths in a URL argument are jail-checked.Presets.
filesystem: read tools and the standard filesystem tools are allowed,delete_fileneeds approval.git: read tools,git_add,git_commit,git_create_branchandgit_checkoutare allowed;git_push,git_resetandgit_mergeneed approval.fetch: setsread_only, sohttp_post,http_put,http_deleteandhttp_patchare blocked;fetch,http_get,read_urlandweb_searchare allowed.sqlite:read_query,list_tables,describe_tableandshow_schemaare allowed,write_query,execute_query,create_tableanddrop_tableneed approval.memory:read_graph,search_nodesandopen_nodesare allowed, the tools that create, delete or add need approval. The pathless tools ofsqlite,memoryandfetchare exempted from the path requirement by the preset, not by their name. Without the preset they are unknown tools.Argument names that look like paths but are not can be listed in
ignore_path_keys. That is an operator decision: the keys are ignored for every tool of the policy. The presets ignore keys for their own tools only: git fortarget,revision,branch_nameand similar (ongit_*tools), memory forfromandto(on the memory tools).New files in directories that do not exist yet are blocked, because the parent folder cannot be resolved. Create the folder first.
Platform status
Linux: the test suite passes (
cargo test --workspace --all-targets).macOS and Windows: the same tests run in CI. Windows-specific protections (UNC, NT namespace, reserved device names,
CONIN$) and macOS terminal handling have not been checked by hand on real systems. Treat them as partly tested.Hardlink checks work on Unix only.
Development
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-targets --all-featuresTwo PowerShell scripts drive the release binary against the built-in mock server (cargo build --release --bin moat --bin mock_server first):
scripts/redteam_simulation.ps1: 33 attack cases (UNC and NT paths, shell injection, traversal, read-only mode, audit log).scripts/dry_run_simulation.ps1: monitor mode and the--strictaudit gate.
They default to the Windows paths under target\release. On Linux and macOS pass -MoatPath/-MockServerPath (redteam) or -MoatBin/-MockBin (dry run).
Crates:
Crate | Content |
| policy engine, path checks, secret masking, audit chain |
| stdio proxy, mock server for tests |
| terminal prompts, diffs, approval cache |
| the |
License
Available Tools
16 toolsappend_fileAppend FileA
Append text to the end of a file, creating the file if it does not exist. The existing content is never changed or replaced. The text is appended exactly as given, with no newline added before or after it, so end it with a newline if the next append should start on a new line. Only works within allowed directories.
Inputs: path (required), content (required). Returns: content
copy_fileCopy FileAIdempotent
Copy a file to a new location, without reading its content into the conversation. Copies one regular file, keeping its permissions and modification time; directories are not copied. If the destination exists, the operation will fail: it never overwrites. Both source and destination must be within allowed directories.
Inputs: source (required), destination (required). Returns: content
create_directoryCreate DirectoryAIdempotent
Create a new directory or ensure a directory exists. Can create multiple nested directories in one operation. If the directory already exists, this operation will succeed silently. Perfect for setting up directory structures for projects or ensuring required paths exist. Only works within allowed directories.
Inputs: path (required). Returns: content
directory_treeDirectory TreeBRead-onlyIdempotent
Get a recursive tree view of files and directories as a JSON structure. Each entry includes 'name', 'type' (file/directory), and 'children' for directories. Files have no children array, while directories always have a children array (which may be empty), except at the last level when 'depth' limits the tree: those directories are not read and have no children array. The output is formatted with 2-space indentation for readability. Only works within allowed directories.
Inputs: path (required), depth, excludePatterns. Returns: content
edit_fileEdit FileADestructive
Make line-based edits to a text file. Edits apply in order, each to the result of the ones before it, and each replaces the first match of its oldText with newText. oldText must match the file's text exactly, except that line endings (LF or CRLF) never matter and, when there is no exact match, a run of whole lines matches if each line is equal once leading and trailing whitespace is ignored (newText then takes the file's indentation). Whitespace inside a line must match. If any edit has no match, nothing is written and the error shows the closest lines of the file, numbered, to copy oldText from. Returns a git-style diff showing the changes made. Only works within allowed directories.
Inputs: path (required), edits (required), dryRun. Returns: content
get_file_infoGet File InfoARead-onlyIdempotent
Retrieve detailed metadata about a file or directory. Returns comprehensive information including size, creation time, last modified time, permissions, type and hard-link count. This tool is perfect for understanding file characteristics without reading the actual content. Only works within allowed directories.
Inputs: path (required). Returns: content
list_allowed_directoriesList Allowed DirectoriesARead-onlyIdempotent
Returns the list of directories that this server is allowed to access. Subdirectories within these allowed directories are also accessible. Use this to understand which directories and their nested paths are available before trying to access files.
Inputs: no named parameters. Returns: content
list_directoryList DirectoryARead-onlyIdempotent
List the files and directories directly inside a path, each marked [FILE] or [DIR]. Use it to see what a directory contains; when you also need each entry's size or want entries sorted by size, use list_directory_with_sizes instead, and for a recursive view use directory_tree. Returns one line per entry. Only works within allowed directories.
Inputs: path (required). Returns: content
list_directory_with_sizesList Directory with SizesARead-onlyIdempotent
List the files and directories directly inside a path with each file's size, marked [FILE] or [DIR], sorted by name or by size, largest first (sortBy). Use it when sizes matter, such as finding the largest files; for names only, use list_directory, which returns less text. Returns one line per entry, followed by the totals. Only works within allowed directories.
Inputs: path (required), sortBy. Returns: content
move_fileMove FileADestructive
Move or rename files and directories. Can move files between directories and rename them in a single operation. If the destination exists, the operation will fail. Works across different directories and can be used for simple renaming within the same directory. Both source and destination must be within allowed directories.
Inputs: source (required), destination (required). Returns: content
read_fileRead File (Deprecated)ARead-onlyIdempotent
Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead.
Inputs: path (required), head, tail. Returns: content
read_media_fileRead Media FileARead-onlyIdempotent
Read a file and return it as a base64-encoded content block with its MIME type. Image and audio files are returned as image/audio content; any other file type is returned as an embedded resource. Only works within allowed directories.
Inputs: path (required). Returns: content
read_multiple_filesRead Multiple FilesARead-onlyIdempotent
Read the contents of multiple files simultaneously. This is more efficient than reading files one by one when you need to analyze or compare multiple files. Each file's content is returned with its path as a reference. Failed reads for individual files won't stop the entire operation. Only works within allowed directories.
Inputs: paths (required). Returns: content
read_text_fileRead Text FileARead-onlyIdempotent
Read the complete contents of a file from the file system as text. Handles various text encodings and provides detailed error messages if the file cannot be read. Use this tool when you need to examine the contents of a single file. Use the 'head' parameter to read only the first N lines of a file, or the 'tail' parameter to read only the last N lines of a file. Operates on the file as text regardless of extension. Only works within allowed directories.
Inputs: path (required), head, tail. Returns: content
search_filesSearch FilesARead-onlyIdempotent
Find files and directories by NAME, not by content: this tool never reads or searches inside files. It walks the tree under 'path' and matches a glob pattern against each entry's path relative to 'path' (case-sensitive). Use '.ext' to match entries directly under 'path', and '**/.ext' or '**/name' to match at any depth. Returns full paths to all matching items. Great for finding files when you don't know their exact location. Only searches within allowed directories.
Inputs: path (required), pattern (required), excludePatterns. Returns: content
write_fileWrite FileADestructiveIdempotent
Create a new file or completely overwrite an existing file with new content. Use with caution as it will overwrite existing files without warning. Handles text content with proper encoding. Only works within allowed directories.
Inputs: path (required), content (required). Returns: content
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 16 tools
The deprecated read_file sits alongside read_text_file with the same purpose, forcing the agent to remember which to use; the three listing tools (list_directory, list_directory_with_sizes, directory_tree) also overlap. Descriptions do a good job of pointing to the right variant in each case, but the deprecated duplicate is a real misselection hazard.
Nearly all names follow a snake_case verb_noun pattern (read_file, write_file, create_directory, list_directory, get_file_info). The main deviations are the bare noun 'directory_tree' and the adjective in 'list_allowed_directories', which are readable but break the pattern slightly.
16 tools is on the heavy side of the suggested 3-15 band, but a filesystem server genuinely needs read/write/list/search/metadata coverage. The deprecated read_file is a wasted slot that could be removed to tighten the set.
Core read/write/move/copy/edit/directory operations are well covered, but there is no delete/remove operation at all, which is a notable lifecycle gap for a filesystem server. Content search (grep) is also absent — search_files is explicitly name-only — so agents can hit dead ends on common tasks.
Maintenance
Related MCP Connectors
Security & DLP proxy for MCP: tool-poisoning scans, PII redaction on tool args/results. Beta.
MCP server for mandates, delegation, policy-gated execution, credential grants, and audit.
One MCP server for all your MCP servers: code mode, per-tool permissions, approvals and audit.
Security audit for MCP servers: command injection, unsafe file access, secrets, prompt injection.
11
Related MCP Servers
AlicenseNot gradedqualityCmaintenanceGoverns any stdio MCP server by interposing between the agent and the server, enforcing policy on every tools/call and refusing denied actions before they reach the upstream server.18 npmApache 2.0- AlicenseNot gradedqualityDmaintenanceA local-first stdio proxy for MCP servers that traps destructive tool calls and holds them for manual commit or discard, preventing accidental mutations.AGPL 3.0
- AlicenseNot gradedqualityBmaintenanceSits in front of any MCP server to enforce allow/ask/block policies on tool calls, paths, shell commands, and network domains, with local approval prompts and an audit log.MIT
- AlicenseNot gradedqualityCmaintenanceA transparent MCP stdio proxy that sits between an agent client and a real MCP server, intercepting tools/call requests to enforce runtime guardrails derived from the same YAML rules used for CI regression testing. It blocks forbidden, out-of-whitelist, looping, or non-idempotent tool invocations with JSON-RPC errors and writes every decision to an audit log.1MIT