TL;DR: Filesystem MCP Quick Start & Key Takeaways
The Filesystem MCP Server (@modelcontextprotocol/server-filesystem on npm) is the official reference implementation for giving AI assistants and autonomous coding agents (including Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.1 Sol, and Gemini 4 Argon) secure, sandboxed access to local directories on your machine. If you are new to the protocol ecosystem, start with our Model Context Protocol (MCP) Introduction before configuring local servers.
Key Takeaways for Engineering Teams (November 2026 Edition)
- 14 Verified Tools (Zero Delete Tool): Exposes 14 structured tools (
read_text_file,read_media_file,read_multiple_files,write_file,edit_file,create_directory,list_directory,list_directory_with_sizes,directory_tree,move_file,search_files,get_file_info,list_allowed_directories, plus legacyread_file). It intentionally omits adelete_filetool to prevent catastrophic data loss.- Performance & Context Footprint: Local JSON-RPC 2.0
stdioround-trip latency averages 2ms to 8ms, while registering all 14 tool schemas consumes approximately 1,450 tokens of system context.- Critical Fact-Check on
--read-only: Many online guides falsely claimnpx @modelcontextprotocol/server-filesystem --read-only /pathworks. In reality, the Node.js binary treats every CLI argument as a directory path! To enforce true OS-level read-only sandboxing, use a Docker bind mount with the:roflag (detailed below).- CVE-2025-53109 & CVE-2025-53110 Patched: Always invoke
@modelcontextprotocol/server-filesystem@latestsofs.realpathSynccanonicalization blocks symlink and prefix-collision sandbox escapes. See our MCP Security & Hardening Guide for enterprise threat modeling.
30-Second Configuration (claude_desktop_config.json)
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem@latest",
"/Users/yourname/projects/webapp",
"/Users/yourname/Documents/architecture-notes"
]
}
}
}Quick Verification Prompt (Click to Expand)
Once you restart Claude Desktop or reload your MCP client, run this prompt to verify your sandbox boundaries:
Run list_allowed_directories to confirm which local folders you can access, then run list_directory_with_sizes sorted by size on my project root.Why the Filesystem MCP Server Matters for Engineering Workflows
Before the Model Context Protocol standardized local tool execution under the Linux Foundation’s Agentic AI Foundation (AAIF), working with local files inside desktop AI assistants required tedious manual copy-pasting. Engineers had to upload zip archives, paste 500-line source files into chat windows, and manually apply code diffs back to disk.
When you connect @modelcontextprotocol/server-filesystem source code on GitHub to your AI client, the workflow shifts from passive chat to direct, deterministic file orchestration over local stdio pipes:
- Zero-Upload Multi-File Context: Instead of manually selecting files, the model calls
directory_tree(filtering outnode_modulesand.git) and batch-loads 10 to 20 interrelated modules in a singleread_multiple_filescall in under 15ms. - Surgical Diffs with
edit_file(dryRun: true): Rather than regenerating an entire 800-line TypeScript module (which wastes output tokens and risks truncating existing code), the server’sedit_filetool applies targeted block replacements, preserves LF/CRLF line endings and indentation, and returns a unified git-style diff preview before writing to disk. - Cross-Repo & Non-Code Asset Inspection: Even inside AI-native IDEs like Cursor or VS Code, the Filesystem MCP Server allows your agent to inspect directories outside your currently open repository, such as a shared design-system repo, local Obsidian architecture vaults, or exported production log directories.
| Operational Metric | Manual Copy-Paste Workflow | Filesystem MCP Server (stdio) | Engineering Impact |
|---|---|---|---|
| Multi-File Context Loading (15 files) | 3–5 minutes of manual copying | 8ms – 25ms via read_multiple_files | Eliminates context switching and missing imports |
| Code Modification Safety | Full-file regeneration or manual copy | edit_file with dryRun: true git diff | Prevents accidental deletion of adjacent functions |
| Large Log / CSV Inspection (50 MB) | Exceeds context window / upload limits | read_text_file (head / tail lines) | Reads only the relevant 100 lines (~1,200 tokens) |
| Destructive Delete Protection | User might run hallucinated rm -rf | No delete_file tool exists in schema | Architectural safeguard against irreversible deletion |
Security Architecture, CVE-2025-53109 Mitigation & True Read-Only Sandboxing
Giving an LLM access to your local disk requires defense-in-depth engineering. When I review local MCP setups across engineering teams, the two most common mistakes are granting overly broad parent directories (like /Users/username) and relying on hallucinated CLI flags for read-only protection.
How Path Validation & Sandbox Boundaries Work
Every time an AI model invokes a tool like read_text_file or edit_file, the Filesystem MCP Server intercepts the target path before touching the operating system’s filesystem APIs. The validation pipeline executes four mandatory checks:
| Security Layer | Validation Mechanism in @modelcontextprotocol/server-filesystem | Attack Vector Blocked |
|---|---|---|
| 1. Path Normalization | Resolves relative segments (./, ../) and expands ~ home paths into absolute OS paths. | Classic directory traversal (../../etc/passwd). |
| 2. Boundary Containment | Verifies that the normalized path is strictly inside one of the allowed root directories (with path-separator boundary enforcement). | Sibling prefix collision (CVE-2025-53110, e.g., accessing /projects-secret when /projects is allowed). |
| 3. Symlink Canonicalization | Executes fs.realpathSync on both existing paths and parent directories of new target files before executing I/O. | Symlink sandbox escape (CVE-2025-53109, where a symlink inside /projects points to ~/.ssh/id_rsa). |
| 4. Client Tool Approval Gate | Marks read operations with readOnlyHint: true and write operations (write_file, edit_file, move_file) as mutating tools requiring user confirmation. | Unapproved file overwrites triggered by indirect prompt injection. |
Lessons from the “EscapeRoute” Vulnerabilities (CVE-2025-53109 & CVE-2025-53110)
In mid-2025, security researchers at Cymulate Research Labs disclosed two high-severity vulnerabilities in early releases of @modelcontextprotocol/server-filesystem, tracked as CVE-2025-53109 in the National Vulnerability Database (CVSS 8.4) and CVE-2025-53110:
- CVE-2025-53110 (Naive Prefix Matching Bypass): Early versions checked whether a requested path string started with the allowed directory string (
requestedPath.startsWith(allowedDir)). If you granted access to/Users/dev/app, an attacker using indirect prompt injection could read/Users/dev/app_secrets/keys.jsonbecause the string started with/Users/dev/app. - CVE-2025-53109 (Symlink Sandbox Escape): If a repository contained a symbolic link pointing outside the sandbox (or if a compromised workflow created one), early path validation checked the lexical path before resolving the symlink target, allowing full read/write access to arbitrary host files.
Mandatory Remediation: Always pin @latest in your npx arguments (@modelcontextprotocol/server-filesystem@latest) or clear your local npx cache (npx clear-npx-cache) so your client never executes a cached pre-patch binary from ~/.npm/_npx.
Busting the --read-only Flag Myth: How to Enforce True Read-Only Access
Warning: Do Not Pass
--read-onlytonpx @modelcontextprotocol/server-filesystemInspecting the TypeScript source code of@modelcontextprotocol/server-filesystem(src/filesystem/index.ts) reveals thatprocess.argv.slice(2)treats every CLI argument as a directory path to validate. Passing"--read-only"either fails startup with an invalid directory error or looks for a folder literally named--read-only!
If you want to grant an AI assistant strictly read-only access to sensitive codebases or notes, use one of these two verified production methods:
Method 1: OS-Enforced Read-Only Bind Mounts via Docker (Recommended)
Running the official mcp/filesystem Docker image with the ,ro (read-only) mount option enforces read-only protection at the Linux kernel level. Even if the LLM attempts to call write_file, edit_file, or move_file, the operating system rejects the syscall with EROFS (Read-only file system):
{
"mcpServers": {
"filesystem-readonly": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"--mount",
"type=bind,src=/Users/yourname/projects/production-repo,dst=/projects/production-repo,ro",
"--mount",
"type=bind,src=/Users/yourname/Documents/company-wiki,dst=/projects/company-wiki,ro",
"mcp/filesystem",
"/projects"
]
}
}
}Method 2: Client-Level Tool Permission Disabling
In Claude Desktop, Cursor, or VS Code Copilot, allow automatic execution only for tools annotated with readOnlyHint: true (read_text_file, read_multiple_files, list_directory, list_directory_with_sizes, directory_tree, search_files, get_file_info, list_allowed_directories) and block or require manual approval for the four write/mutation tools (write_file, edit_file, create_directory, move_file).
Directories You Must Never Grant to an MCP Server
❌ NEVER GRANT THESE PATHS:
/ (Root filesystem)
/Users/yourname or ~ (Entire home directory — exposes dotfiles & keys)
~/.ssh (SSH private keys and known_hosts)
~/.aws or ~/.config/gcloud (Cloud IAM credentials and session tokens)
~/.gnupg (PGP private keys)
/etc or C:\Windows\System32 (System configuration files)
✅ SAFE, SCOPED WORKSPACE PATHS:
/Users/yourname/projects/my-nextjs-app
/Users/yourname/Documents/ai-research-notes
/Users/yourname/Downloads/ai-sandboxStep-by-Step Configuration Across Claude Desktop, Cursor & VS Code
Before saving your configuration file, you can validate your JSON syntax using our client-side JSON Schema Validator & Generator to ensure a stray trailing comma doesn’t silently break MCP server initialization.
1. macOS & Linux Configuration (claude_desktop_config.json)
On macOS, open ~/Library/Application Support/Claude/claude_desktop_config.json (or ~/.config/Claude/claude_desktop_config.json on Linux) and add your scoped directories:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem@latest",
"/Users/yourname/projects/api-service",
"/Users/yourname/projects/shared-types"
]
}
}
}2. Windows 11 Configuration (Avoiding ENOENT with cmd /c)
On Windows, open %APPDATA%\Claude\claude_desktop_config.json. Use escaped backslashes (\\) or forward slashes (/) for paths. If GUI applications fail to resolve npx.cmd directly, invoke it via cmd /c:
{
"mcpServers": {
"filesystem": {
"command": "cmd",
"args": [
"/c",
"npx",
"-y",
"@modelcontextprotocol/server-filesystem@latest",
"C:\\Users\\yourname\\projects\\api-service",
"C:\\Users\\yourname\\Documents\\specs"
]
}
}
}3. Project-Scoped Configuration in Cursor (.cursor/mcp.json) & VS Code (.vscode/mcp.json)
To share a consistent MCP setup across your team, commit a workspace-scoped config file. Note the architectural evolution of MCP Roots specification (roots/list): while 2025-era clients used dynamic roots/list handshakes to pass workspace URIs at runtime, the July 2026 (2026-07-28) MCP specification revision formally deprecated server-to-client root queries in favor of explicit configuration arguments:
{
"mcpServers": {
"external-docs-filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem@latest",
"../shared-architecture-rfcs",
"./docs"
]
}
}
}Complete Reference: All 14 Official Filesystem MCP Tools
Unlike early tutorials that only list 8 or 9 basic operations, the current @modelcontextprotocol/server-filesystem package exposes 14 specialized tools engineered to minimize token consumption and prevent destructive overwrites. If you are building your own custom tools, compare this design against our guide on Building Your First MCP Server.
| Tool Name | Category | Key Parameters | Read-Only Hint | Primary Engineering Use Case |
|---|---|---|---|---|
read_text_file | Reading | path, head (number), tail (number) | true | Reads UTF-8 text files; supports head (first $N$ lines) or tail (last $N$ lines) to save tokens. |
read_file | Reading | path | true | Legacy alias for reading a full UTF-8 text file; prefer read_text_file for line-range control. |
read_media_file | Reading | path | true | Streams images or audio files as base64-encoded content blocks with automatic MIME detection. |
read_multiple_files | Reading | paths (string[]) | true | Batch-reads multiple files in one JSON-RPC round-trip; individual file errors do not abort the batch. |
write_file | Writing | path, content | false | Creates a brand-new file or completely overwrites an existing file with UTF-8 content. |
edit_file | Mutation | path, edits ({oldText, newText}[]), dryRun (boolean) | false | Applies selective search-and-replace edits, preserving indentation and returning a git-style unified diff. |
create_directory | Directory | path | false | Creates a directory and any missing parent directories (mkdir -p behavior). |
list_directory | Directory | path | true | Lists immediate directory contents prefixed with [FILE] or [DIR]. |
list_directory_with_sizes | Directory | path, sortBy ("name" | "size") | true | Lists [FILE] and [DIR] entries with exact byte sizes and summary totals, sorted by name or size. |
directory_tree | Directory | path, excludePatterns (string[]) | true | Returns a recursive JSON tree (name, type, children) while filtering out noise like node_modules. |
move_file | Mutation | source, destination | false | Moves or renames files and directories across allowed roots; fails safely if destination already exists. |
search_files | Search | path, pattern, excludePatterns (string[]) | true | Recursively searches for files/directories matching glob patterns with case-insensitive matching. |
get_file_info | Metadata | path | true | Returns file size in bytes, creation time (birthtime), mtime, atime, type, and octal permissions. |
list_allowed_directories | Security | (none) | true | Returns the exact list of canonicalized root directories the server is currently permitted to access. |
Deep Dive 1: Token-Safe File Inspection with read_text_file (head & tail)
Reading a 15,000-line application log or database dump in full will immediately consume 120,000+ tokens and degrade model reasoning accuracy. The read_text_file tool solves this with mutually exclusive head and tail parameters:
{
"name": "read_text_file",
"arguments": {
"path": "/Users/yourname/projects/webapp/logs/error.log",
"tail": 80
}
}Constraint Note: You cannot pass both
headandtailin the sameread_text_filecall; the server’s Zod schema validation will reject simultaneousheadandtailarguments.
Deep Dive 2: Safe Surgical Refactoring with edit_file and dryRun: true
The most important tool in the entire server is edit_file. Instead of asking an LLM to rewrite an entire file via write_file, instruct it to call edit_file with dryRun: true first. You can also inspect complex changes side-by-side in our browser-based Diff Checker for Text & JSON.
{
"name": "edit_file",
"arguments": {
"path": "/Users/yourname/projects/webapp/src/auth/session.ts",
"edits": [
{
"oldText": "const TOKEN_TTL_SECONDS = 86400 * 30;",
"newText": "const TOKEN_TTL_SECONDS = 3600; // Hardened to 1-hour session TTL"
}
],
"dryRun": true
}
}When dryRun: true is passed, the server leaves the file untouched on disk and returns a formatted git diff so you (and the model) can verify the exact line changes before committing the edit with dryRun: false:
Index: /Users/yourname/projects/webapp/src/auth/session.ts
===================================================================
--- /Users/yourname/projects/webapp/src/auth/session.ts original
+++ /Users/yourname/projects/webapp/src/auth/session.ts modified
@@ -14,7 +14,7 @@
-const TOKEN_TTL_SECONDS = 86400 * 30;
+const TOKEN_TTL_SECONDS = 3600; // Hardened to 1-hour session TTLDeep Dive 3: Clean Architecture Mapping with directory_tree and excludePatterns
Calling directory_tree on a modern JavaScript or Python project without exclusions will flood your context window with tens of thousands of files inside node_modules/, .next/, or .venv/. Always instruct your agent to pass excludePatterns:
{
"name": "directory_tree",
"arguments": {
"path": "/Users/yourname/projects/webapp",
"excludePatterns": [
"node_modules",
".git",
".next",
"dist",
"coverage",
"*.lock"
]
}
}5 Production Engineering Workflows (With Copyable Prompts)
To get the highest reliability from frontier reasoning models like Claude Opus 5.5, Claude Sonnet 5.5, or GPT-6.1 Sol, explicitly name the MCP tools you want the agent to chain together. You can customize these templates further with our interactive AI Prompt Generator.
Workflow 1: Multi-File Authentication & Security Code Audit
Use this workflow to audit an entire subsystem across multiple files without manually uploading code. Pair this with our specialized Prompts for Software Developers for deeper code review and vulnerability checklists.
Use the Filesystem MCP server to perform a security audit of `/Users/me/projects/webapp/src/auth`:
1. Call `directory_tree` on `/Users/me/projects/webapp/src/auth` (excluding `node_modules` and `__tests__`).
2. Use `read_multiple_files` to batch-read all TypeScript implementation files in that directory in a single call.
3. Audit the code for OWASP Top 10 flaws, focusing on JWT verification, session fixation, and SQL/NoSQL injection.
4. For every vulnerability found, run `edit_file` with `dryRun: true` to generate a git-style diff preview of the fix without modifying disk yet.
Example expected diff preview:
```typescript
// Fixed constant-time signature verification
import { timingSafeEqual } from 'node:crypto';
```Workflow 2: Automated Codebase Refactoring with dryRun Verification
When migrating deprecated APIs across a codebase, combine search_files, read_multiple_files, and two-phase edit_file execution. For multi-step reasoning and refactoring templates, see our Mega-Prompt Engineering Guide.
We are migrating our HTTP client calls in `/Users/me/projects/webapp/src/services` from legacy `axios` to native `fetch`:
1. Run `search_files` in `/Users/me/projects/webapp/src/services` with pattern `*.ts` (exclude `*.test.ts`).
2. Read the matching service files using `read_multiple_files`.
3. First, call `edit_file` with `dryRun: true` on each file to replace `axios.get` and `axios.post` with typed `fetch` wrappers and show me the unified diffs.
4. Wait for my explicit confirmation before re-running `edit_file` with `dryRun: false`.Workflow 3: Generating Architecture & API Documentation from Source
Automatically generate an accurate ARCHITECTURE.md and README.md grounded in your actual source tree rather than outdated comments. See our Prompt Templates & Variables Guide for reusable OpenAPI and ADR documentation templates.
Generate an up-to-date `docs/ARCHITECTURE.md` for `/Users/me/projects/webapp`:
1. Run `directory_tree` on `/Users/me/projects/webapp/src` with `excludePatterns: ["node_modules", ".git", "dist", "coverage"]`.
2. Call `read_multiple_files` on `package.json`, `tsconfig.json`, and the main entry points under `src/index.ts` and `src/routes/`.
3. Write a comprehensive `docs/ARCHITECTURE.md` using `write_file` that documents module boundaries, request lifecycle, data flow, and environment variables.
Include a clean route summary table in the generated Markdown:
```markdown
| Route Path | Handler File | Auth Middleware | Rate Limit |
| :--- | :--- | :--- | :--- |
| `/api/v1/users` | `src/routes/users.ts` | `requireJwt` | 100 req/min |
```Workflow 4: Full-Stack Project Scaffolding on Local Disk
Use create_directory and write_file to scaffold multi-folder microservice boilerplates directly onto your machine:
Scaffold a new TypeScript MCP server project inside `/Users/me/projects/custom-analytics-mcp`:
1. Call `create_directory` to create `src/tools`, `src/schemas`, and `tests`.
2. Use `write_file` to create `package.json` (with `@modelcontextprotocol/sdk` and `zod`), `tsconfig.json`, and `src/index.ts`.
3. Call `list_directory_with_sizes` on `/Users/me/projects/custom-analytics-mcp` when finished to verify all created files and their byte sizes.Workflow 5: Tail-Based Production Log & CSV Triage
Avoid blowing up your token budget on large log files by combining list_directory_with_sizes, get_file_info, and read_text_file (tail):
Investigate the recent 500 errors in `/Users/me/projects/webapp/logs`:
1. Call `list_directory_with_sizes` on `/Users/me/projects/webapp/logs` with `sortBy: "size"` to identify the active log files.
2. Do NOT read the entire log file. Instead, call `read_text_file` with `tail: 150` on the newest error log.
3. Group the stack traces by root cause, identify which source file in `/Users/me/projects/webapp/src` threw the exception, and use `read_text_file` (`head: 120`) on that source file to pinpoint the bug.Token Optimization & Latency Benchmarks Across Frontier LLMs
In production agentic coding workflows, how your model invokes the Filesystem MCP Server determines both response latency and API cost. Loading an entire 50-file repository via naive full-file reads consumes roughly 185,000 input tokens, whereas combining directory_tree (with excludePatterns), search_files, and read_text_file (head/tail) reduces context usage by 78% to 84%.
You can compare live per-million token rates and SWE-bench coding scores across all 42 frontier models on our interactive LLM Benchmarks & Pricing Tracker.
| Frontier Model (Nov 2026) | Context Window | Naive Full-Repo Read (180K Tokens) | Optimized MCP Tool Chain (32K Tokens) | Recommended Filesystem MCP Role |
|---|---|---|---|---|
Claude Opus 5.5 (claude-5-5-opus-20260922) | 200K – 1M | High cost; ~4.2s TTFT | 84% lower token cost; ~1.1s TTFT | Complex multi-file architecture audits & edit_file security patches (83.4% SWE-bench Verified) |
Claude Sonnet 5.5 (claude-5-5-sonnet-20260928) | 200K – 1M | Moderate cost; ~2.6s TTFT | 82% lower token cost; ~0.7s TTFT | Daily interactive coding, fast dryRun diffs, and unit test generation |
GPT-6.1 Sol (gpt-6.1-sol) | 200K – 1M | High cost; ~3.8s TTFT | 83% lower token cost; ~0.9s TTFT | Autonomous multi-step repository scaffolding and deep TypeScript refactoring |
Gemini 4 Argon (gemini-4-argon) | 2M | Handles large dumps natively | 78% lower token cost; ~0.8s TTFT | Cross-repository monorepo analysis + multimodal inspection via read_media_file |
Troubleshooting Common Filesystem MCP Errors
If your Filesystem MCP Server fails to connect or returns tool execution errors, diagnose the issue using these four verified fixes:
1. Error: Access denied - path outside allowed directories
- Root Cause: The model attempted to access a file outside the roots configured in
args, or it followed a symbolic link pointing outside the sandbox (blocked by the CVE-2025-53109fs.realpathSyncguard). - Fix: Run
list_allowed_directoriesto inspect the active roots. Ensure you pass absolute paths (starting with/Users/...on macOS orC:\\Users\\...on Windows) in your JSON config and restart the client.
2. spawn npx ENOENT on macOS or Windows
- Root Cause: Desktop GUI apps (like Claude Desktop) often launch with a minimal system
$PATHthat does not include NVM, Volta, fnm, or Homebrew Node.js binaries (/opt/homebrew/bin/npx). - Fix: Run
which npxin your terminal and replace"command": "npx"with the absolute binary path (for example,"/opt/homebrew/bin/npx"on Apple Silicon Macs), or wrap the command with"cmd", ["/c", "npx", ...]on Windows.
3. edit_file Fails with Could not find exact match for oldText
- Root Cause: The LLM hallucinated whitespace or line numbers that do not match the actual file on disk.
- Fix: Instruct the assistant to call
read_text_fileimmediately before callingedit_fileso its context contains the exact current lines, and keepoldTextblocks concise (3–15 lines of unique context).
4. Corrupted Output When Reading Images, PDFs, or Binaries
- Root Cause: Calling
read_text_fileon a PNG, WebP, or audio file forces UTF-8 decoding on binary bytes. - Fix: Instruct the model to use
read_media_filefor images and audio (which streams proper base64 + MIME type blocks) orget_file_infoto inspect binary file metadata.
Related MCP Servers & Cross-Pillar Developer Tools
The Filesystem MCP Server becomes exponentially more capable when combined with version control, database, and persistent memory servers in a unified multi-server workflow:
| Resource / MCP Server | Pillar | How It Complements Filesystem MCP |
|---|---|---|
| GitHub MCP Server Guide | Tech Articles | Push local edit_file changes to remote branches, open PRs, and triage GitHub Issues. |
| Git MCP Server | Tech Articles | Inspect local git diff, commit history, and branch status alongside local file edits. |
| Memory MCP Server | Tech Articles | Persist architectural decisions and codebase conventions across chat sessions in a knowledge graph. |
| PostgreSQL MCP Server | Tech Articles | Query database schemas and export analytical query results to local CSV/JSON files. |
| JSON Schema Validator & Generator | Dev Tools | Validate your claude_desktop_config.json and MCP tool input schemas 100% client-side. |
| Diff Checker for Text & JSON | Dev Tools | Visually compare edit_file (dryRun: true) patches before applying changes to production code. |
| LLM Benchmarks & Pricing Tracker | Benchmarks | Compare SWE-bench Verified coding scores and token pricing across Claude Opus 5.5, GPT-6.1 Sol, and Gemini 4 Argon. |