filesystem-context-mcp-server

j0hanz/filesystem-context-mcp-server

3.2

If you are the rightful owner of filesystem-context-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A secure Model Context Protocol (MCP) server designed for filesystem scanning, searching, and analysis, built with TypeScript and the official MCP SDK.

Tools
5
Resources
0
Prompts
0

Filesystem Context MCP Server

A secure, read-only MCP server for filesystem scanning, searching, and analysis with comprehensive security validation.

npm version Node.js TypeScript MCP SDK

One-Click Install

Install with NPX in VS CodeInstall with NPX in VS Code Insiders

Install in Cursor

✨ Features

FeatureDescription
📂 Directory ListingList and explore directory contents with recursive support
🔍 File SearchFind files using glob patterns like **/*.ts
📝 Content SearchSearch text within files using regex with context lines
📊 Directory AnalysisGet statistics, file types, largest files, and recently modified files
🌳 Directory TreeJSON tree structure optimized for AI parsing
📄 File ReadingRead single or multiple files with head/tail and line range support
🖼️ Media File SupportRead binary files (images, audio, video) as base64
🔒 Security FirstPath validation, symlink escape protection, and access control
Parallel OperationsEfficient batch file reading with configurable concurrency

🎯 When to Use

TaskTool
Explore project structurelist_directory
Find specific file typessearch_files
Search for code patterns/textsearch_content
Find code definitionssearch_definitions
Understand codebase statisticsanalyze_directory
Get AI-friendly project overviewdirectory_tree
Read source coderead_file
Batch read multiple filesread_multiple_files
Get file metadata (size, dates)get_file_info
Batch get file metadataget_multiple_file_info
Compute file checksums/hashescompute_checksums
Read images or binary filesread_media_file
Check available directorieslist_allowed_directories

🚀 Quick Start

NPX (Recommended - Zero Config)

# Works in current directory automatically!
npx -y @j0hanz/filesystem-context-mcp@latest

Or specify directories explicitly:

npx -y @j0hanz/filesystem-context-mcp@latest /path/to/your/project

VS Code (with workspace folder)

Add to your VS Code settings (.vscode/mcp.json):

{
  "servers": {
    "filesystem-context": {
      "command": "npx",
      "args": [
        "-y",
        "@j0hanz/filesystem-context-mcp@latest",
        "${workspaceFolder}"
      ]
    }
  }
}

Tip: ${workspaceFolder} automatically uses your current VS Code workspace. You can also omit it and the server will use its current working directory.

Claude Desktop

Add to your Claude Desktop configuration (claude_desktop_config.json):

{
  "mcpServers": {
    "filesystem-context": {
      "command": "npx",
      "args": ["-y", "@j0hanz/filesystem-context-mcp@latest"]
    }
  }
}

Note: Claude Desktop will use the current working directory automatically. No path arguments needed!

📦 Installation

NPX (No Installation)

npx -y @j0hanz/filesystem-context-mcp@latest /path/to/dir1 /path/to/dir2

Global Installation

npm install -g @j0hanz/filesystem-context-mcp
filesystem-context-mcp /path/to/your/project

From Source

git clone https://github.com/j0hanz/filesystem-context-mcp-server.git
cd filesystem-context-mcp-server
npm install
npm run build
node dist/index.js /path/to/your/project

⚙️ Configuration

Directory Resolution (Priority Order)

The server determines which directories to access in this order:

  1. CLI Arguments - Explicitly passed paths take highest priority
  2. MCP Roots Protocol - Directories provided by the MCP client
  3. Current Working Directory - Automatic fallback for plug-and-play experience

This means you can run the server with zero configuration and it will work!

Command Line Arguments

Optionally specify one or more directory paths as arguments:

filesystem-context-mcp /home/user/project /home/user/docs

MCP Roots Protocol

If no CLI arguments are provided, the server will use the MCP Roots protocol to receive allowed directories from the client (if supported).

Zero-Config Mode

If neither CLI arguments nor MCP Roots provide directories, the server automatically uses the current working directory. This makes it truly plug-and-play!

Environment Variables

All configuration values have sensible defaults and are optional. Only configure if you need to tune performance or resource usage.

VariableDefaultRangeDescription
FILESYSTEM_CONTEXT_CONCURRENCYAuto (2x cores)1-100Maximum parallel file operations
TRAVERSAL_JOBS81-50Directory traversal concurrency
REGEX_TIMEOUT10050-1000Regex matching timeout (milliseconds)
MAX_FILE_SIZE10MB1MB-100MBMaximum text file size (bytes)
MAX_MEDIA_SIZE50MB1MB-500MBMaximum media file size (bytes)
MAX_SEARCH_SIZE1MB100KB-10MBMaximum file size for content search
DEFAULT_DEPTH101-100Default maximum recursion depth
DEFAULT_RESULTS10010-10000Default maximum search results
DEFAULT_LIST_MAX_ENTRIES10000100-100000Default max entries for list_directory
DEFAULT_SEARCH_MAX_FILES20000100-100000Default max files to scan in searches
DEFAULT_SEARCH_TIMEOUT30000100-3600000Default search timeout (milliseconds)
DEFAULT_TOP101-1000Default top N items in analysis
DEFAULT_ANALYZE_MAX_ENTRIES20000100-100000Default max entries in analyze_directory
DEFAULT_TREE51-50Default directory tree depth
DEFAULT_TREE_MAX_FILES5000100-200000Default max files in directory tree

💡 Tip: See for detailed environment variable usage examples, configuration profiles, and best practices for different use cases.

🔧 Tools

list_allowed_directories

List all directories that this server is allowed to access.

ParameterTypeRequiredDefaultDescription
(none)---No parameters required

Returns: Array of allowed directory paths.


list_directory

List contents of a directory with optional recursive listing.

ParameterTypeRequiredDefaultDescription
pathstring?-Directory path to list
recursiveboolean?falseList recursively
includeHiddenboolean?falseInclude hidden files
excludePatternsstring[]?[]Patterns to exclude
patternstring?-Glob pattern to include
maxDepthnumber?10Maximum depth for recursive listing (0-100)
maxEntriesnumber?10000Maximum entries to return (1-100,000)
sortBystring?nameSort by: name, size, modified, type
includeSymlinkTargetsboolean?falseInclude symlink target paths

Returns: List of entries with name, type, size, and modified date.


search_files

Search for files (not directories) using glob patterns.

ParameterTypeRequiredDefaultDescription
pathstring-Base directory to search from
patternstring-Glob pattern (e.g., **/*.ts, src/**/*.js)
excludePatternsstring[][]Patterns to exclude
maxResultsnumber100Maximum matches to return (1-10,000)
sortBystringpathSort by: name, size, modified, path
maxDepthnumber-Maximum directory depth to search (1-100)
maxFilesScannednumber20000Maximum files to scan before stopping
timeoutMsnumber30000Timeout in milliseconds (100-3,600,000)

Returns: List of matching files with path, type, size, and modified date.

Example:

{
  "path": "/project",
  "pattern": "**/*.ts",
  "excludePatterns": ["node_modules/**", "dist/**"]
}

read_file

Read the contents of a text file.

ParameterTypeRequiredDefaultDescription
pathstring?-File path to read
encodingstring?utf-8File encoding (utf-8, ascii, base64, etc.)
maxSizenumber?10MBMaximum file size in bytes
skipBinaryboolean?falseReject binary files (use read_media_file instead)
lineStartnumber?-Start line (1-indexed, min 1) for reading a range
lineEndnumber?-End line (1-indexed, inclusive, min 1) for reading a range
headnumber?-Read only first N lines
tailnumber?-Read only last N lines

Note: Cannot specify both head and tail simultaneously. Use lineStart/lineEnd for range reading.

Returns: File contents as text.


read_multiple_files

Read multiple files in parallel for efficient batch operations.

ParameterTypeRequiredDefaultDescription
pathsstring[]-Array of file paths to read (max 100)
encodingstringutf-8File encoding
maxSizenumber10MBMaximum size per file in bytes
maxTotalSizenumber100MBMaximum total size for all files combined
headnumber-Read only first N lines of each file
tailnumber-Read only last N lines of each file
lineStartnumber-Start line (1-indexed) for reading a range
lineEndnumber-End line (inclusive) for reading a range

Returns: Array of file contents with individual success/error status.


get_multiple_file_info

Get metadata for multiple files/directories in parallel.

ParameterTypeRequiredDefaultDescription
pathsstring[]-Array of paths to query (max 100)
includeMimeTypebooleantrueInclude MIME type detection

Returns: Array of file info (name, path, type, size, timestamps, permissions, mimeType) with individual success/error status, plus summary.


compute_checksums

Compute cryptographic checksums for files using memory-efficient streaming.

ParameterTypeRequiredDefaultDescription
pathsstring[]-Array of file paths (max 50)
algorithmstringsha256Hash algorithm: md5, sha1, sha256, sha512
encodingstringhexOutput encoding: hex or base64
maxFileSizenumber100MBSkip files larger than this

Returns: Array of checksums with file sizes, plus summary (total, succeeded, failed).

Use cases:

  • Verify file integrity after transfers
  • Detect duplicate files by comparing hashes
  • Generate checksums for release artifacts

ParameterTypeRequiredDefaultDescription
pathsstring[]-Array of file paths (max 100)
encodingstringutf-8File encoding
maxSizenumber10MBMaximum file size per file
maxTotalSizenumber100MBMaximum total size for all files combined
headnumber-Read only first N lines of each file
tailnumber-Read only last N lines of each file

Note: Use read_file for single files with line ranges (lineStart/lineEnd). Use read_multiple_files for batch operations with head/tail parameters. The batch API does not support line ranges per file.

Returns: Array of results with content or error for each file.


get_file_info

Get detailed metadata about a file or directory.

ParameterTypeRequiredDefaultDescription
pathstring-Path to file or directory

Returns: Metadata including name, type, size, created/modified/accessed timestamps, permissions, MIME type, and symlink target (if applicable).


search_content

Search for text content within files using regular expressions.

ParameterTypeRequiredDefaultDescription
pathstring-Base directory to search in
patternstring-Regex pattern to search for
filePatternstring**/*Glob pattern to filter files
excludePatternsstring[][]Glob patterns to exclude
caseSensitivebooleanfalseCase-sensitive search
maxResultsnumber100Maximum number of results (1-10,000)
maxFileSizenumber1MBMaximum file size to scan
maxFilesScannednumber20000Maximum files to scan before stopping
timeoutMsnumber30000Timeout in milliseconds (100-3,600,000)
skipBinarybooleantrueSkip binary files
includeHiddenbooleanfalseInclude hidden files and directories
contextLinesnumber0Lines of context before/after match (0-10)
wholeWordbooleanfalseMatch whole words only
isLiteralbooleanfalseTreat pattern as literal string (escape special)

Returns: Matching lines with file path, line number, content, and optional context.

Example:

{
  "path": "/project/src",
  "pattern": "TODO|FIXME",
  "filePattern": "**/*.ts",
  "contextLines": 2
}

search_definitions

Find code definitions (classes, functions, interfaces, types, enums, variables) in TypeScript/JavaScript files without manual regex construction.

ParameterTypeRequiredDefaultDescription
pathstring-Base directory to search in
namestring-Definition name to search for
typestring-Definition type to find: class, function, interface, type, enum, variable
caseSensitivebooleantrueCase-sensitive name matching
maxResultsnumber100Maximum number of results (1-10,000)
excludePatternsstring[][]Glob patterns to exclude
includeHiddenbooleanfalseInclude hidden files and directories
contextLinesnumber0Lines of context before/after match (0-10)

Returns: List of definitions with name, type (class/function/interface/type/enum/variable), file path, line number, exported status, and code preview.

Use cases:

  • Find by name: Search for a specific definition like UserService
  • Discovery mode: Find all definitions of a type (e.g., all interfaces)
  • Combined: Find definitions matching a name pattern and type

Examples:

{
  "path": "/project/src",
  "name": "UserService"
}
{
  "path": "/project/src",
  "type": "interface"
}
{
  "path": "/project/src",
  "name": "Handler",
  "type": "class"
}

analyze_directory

Analyze a directory structure and return statistics.

ParameterTypeRequiredDefaultDescription
pathstring-Directory to analyze
maxDepthnumber10Maximum depth to analyze (0-100)
topNnumber10Number of top items to return (max 1000)
maxEntriesnumber?20000Maximum entries to scan (1-100,000)
excludePatternsstring[][]Glob patterns to exclude
includeHiddenbooleanfalseInclude hidden files and directories

Returns: Statistics including total files/directories, total size, file type distribution, largest files, and recently modified files.


directory_tree

Get a JSON tree structure of a directory, optimized for AI parsing.

ParameterTypeRequiredDefaultDescription
pathstring-Directory path to build tree from
maxDepthnumber5Maximum depth to traverse (0-50)
excludePatternsstring[][]Glob patterns to exclude
includeHiddenbooleanfalseInclude hidden files and directories
includeSizebooleanfalseInclude file sizes in the tree
maxFilesnumber-Maximum total files to include (max 100,000)

Returns: Hierarchical tree structure with file/directory nodes.


read_media_file

Read a binary/media file and return it as base64-encoded data.

ParameterTypeRequiredDefaultDescription
pathstring-Path to the media file
maxSizenumber50MBMaximum file size in bytes (max 500MB)

Supported formats: Images (PNG, JPG, GIF, WebP, SVG, etc.), Audio (MP3, WAV, FLAC, etc.), Video (MP4, WebM, etc.), Fonts (TTF, WOFF, etc.), PDFs, and more.

Returns: Base64-encoded data with MIME type and size.

🔌 Client Configuration

VS Code

Add to .vscode/mcp.json (recommended) or .vscode/settings.json:

{
  "servers": {
    "filesystem-context": {
      "command": "npx",
      "args": [
        "-y",
        "@j0hanz/filesystem-context-mcp@latest",
        "${workspaceFolder}"
      ]
    }
  }
}

Note: ${workspaceFolder} is expanded by VS Code to the current workspace path.

Claude Desktop

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "filesystem-context": {
      "command": "npx",
      "args": ["-y", "@j0hanz/filesystem-context-mcp@latest"]
    }
  }
}
Cursor

Add to Cursor's MCP configuration:

{
  "mcpServers": {
    "filesystem-context": {
      "command": "npx",
      "args": ["-y", "@j0hanz/filesystem-context-mcp@latest"]
    }
  }
}
Codex

Add to ~/.codex/config.toml:

Basic Configuration (auto-detects current directory):

[mcp_servers.filesystem-context]
command = "npx"
args = ["-y", "@j0hanz/filesystem-context-mcp@latest"]

Configuration with Explicit Directory:

[mcp_servers.filesystem-context]
command = "npx"
args = ["-y", "@j0hanz/filesystem-context-mcp@latest", "/path/to/your/project"]

Configuration with Multiple Directories:

[mcp_servers.filesystem-context]
command = "npx"
args = ["-y", "@j0hanz/filesystem-context-mcp@latest", "/path/to/project1", "/path/to/project2"]

Note: You can access the config file via Codex IDE by clicking the gear icon → "Codex Settings > Open config.toml". If no directories are specified, it will use the current working directory automatically.

Windsurf

Add to Windsurf's MCP configuration:

{
  "mcpServers": {
    "filesystem-context": {
      "command": "npx",
      "args": ["-y", "@j0hanz/filesystem-context-mcp@latest"]
    }
  }
}

🔒 Security

This server implements multiple layers of security:

ProtectionDescription
Access ControlOnly explicitly allowed directories are accessible
Path ValidationAll paths are validated before any filesystem operation
Symlink ProtectionSymlinks that resolve outside allowed directories are blocked
Path Traversal PreventionAttempts to escape via ../ are detected and blocked
Read-Only OperationsServer only performs read operations—no writes, deletes, or modifications
Safe RegexRegular expressions are validated to prevent ReDoS attacks
Size LimitsConfigurable limits prevent resource exhaustion

Security Model

┌─────────────────────────────────────────────────────────┐
│                    MCP Client                           │
└─────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│            Filesystem Context MCP Server                │
│  ┌───────────────────────────────────────────────────┐  │
│  │              Path Validation Layer                │  │
│  │  • Normalize paths                                │  │
│  │  • Check against allowed directories              │  │
│  │  • Resolve and validate symlinks                  │  │
│  │  • Block traversal attempts                       │  │
│  └───────────────────────────────────────────────────┘  │
│                         │                               │
│                         ▼                               │
│  ┌───────────────────────────────────────────────────┐  │
│  │            Read-Only File Operations              │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│              Allowed Directories Only                   │
│  /home/user/project  ✅                                 │
│  /home/user/docs     ✅                                 │
│  /etc/passwd         ❌ (blocked)                       │
│  ../../../etc        ❌ (blocked)                       │
└─────────────────────────────────────────────────────────┘

🛠️ Development

Prerequisites

  • Node.js >= 20.0.0
  • npm

Scripts

CommandDescription
npm run buildCompile TypeScript to JavaScript
npm run devWatch mode with tsx
npm run startRun compiled server
npm run testRun tests with Vitest
npm run test:watchRun tests in watch mode
npm run test:coverageRun tests with coverage report
npm run lintRun ESLint
npm run formatFormat code with Prettier
npm run type-checkTypeScript type checking
npm run inspectorTest with MCP Inspector

Project Structure

src/
├── index.ts              # Entry point, CLI argument parsing
├── server.ts             # MCP server setup, roots protocol handling
├── instructions.md       # AI instructions for tool usage (bundled with dist)
├── config/
│   └── types.ts          # Shared TypeScript types
├── lib/
│   ├── constants.ts      # Configuration constants and limits
│   ├── errors.ts         # Error handling utilities
│   ├── file-operations.ts# Core filesystem operations (exports)
│   ├── path-utils.ts     # Path manipulation utilities
│   ├── path-validation.ts# Security: path validation layer
│   ├── fs-helpers.ts     # Low-level filesystem helpers (exports)
│   ├── file-operations/  # Core filesystem operations
│   │   ├── analyze-directory.ts
│   │   ├── directory-helpers.ts
│   │   ├── directory-tree.ts
│   │   ├── file-info.ts
│   │   ├── list-directory.ts
│   │   ├── pattern-validator.ts
│   │   ├── read-media-file.ts
│   │   ├── read-multiple-files.ts
│   │   ├── search-content.ts
│   │   ├── search-definitions.ts
│   │   ├── search-files.ts
│   │   └── sorting.ts
│   ├── fs-helpers/       # Low-level filesystem helpers
│   │   ├── binary-detect.ts
│   │   ├── concurrency.ts
│   │   ├── fs-utils.ts
│   │   ├── readers.ts
│   │   └── readers/      # File reading utilities
│   │       ├── head-file.ts
│   │       ├── line-range.ts
│   │       ├── read-file.ts
│   │       ├── tail-file.ts
│   │       └── utf8.ts
│   └── path-validation/  # Security: path validation
│       ├── allowed-directories.ts
│       ├── errors.ts
│       ├── roots.ts
│       └── validators.ts
├── schemas/
│   ├── common.ts         # Shared Zod schemas
│   ├── input-helpers.ts  # Input validation helpers
│   ├── inputs.ts         # Input validation schemas
│   ├── output-helpers.ts # Output formatting helpers
│   ├── outputs.ts        # Output validation schemas
│   └── index.ts          # Schema exports
├── tools/
│   ├── analyze-directory.ts
│   ├── directory-tree.ts
│   ├── get-file-info.ts
│   ├── list-allowed-dirs.ts
│   ├── list-directory.ts
│   ├── read-file.ts
│   ├── read-media-file.ts
│   ├── read-multiple-files.ts
│   ├── search-content.ts
│   ├── search-definitions.ts
│   ├── search-files.ts
│   ├── tool-response.ts  # Tool response formatting
│   └── index.ts          # Tool registration
└── __tests__/            # Test files
    ├── lib/
    │   ├── errors.test.ts
    │   ├── file-operations.test.ts
    │   ├── fs-helpers.test.ts
    │   └── path-validation.test.ts
    ├── schemas/
    │   └── validators.test.ts
    └── security/
        └── filesystem-boundary.test.ts

Testing with MCP Inspector

npm run inspector

This launches the MCP Inspector for interactive testing of all tools.

❓ Troubleshooting

IssueSolution
"Access denied" errorEnsure the path is within an allowed directory. Use list_allowed_directories to check.
"Path does not exist" errorVerify the path exists. Use list_directory to explore available files.
"File too large" errorUse head or tail parameters for partial reading, or increase maxSize.
"Binary file" warningUse read_media_file for binary files, or set skipBinary=false in content search.
Unexpected directory accessServer defaults to CWD if no args/roots provided. Pass explicit paths to restrict.
Symlink blockedSymlinks that resolve outside allowed directories are blocked for security.
Regex timeoutSimplify the regex pattern or use isLiteral=true for literal string search.

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests and linting (npm run lint && npm run test)
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Code Style

  • Use TypeScript with strict mode
  • Follow ESLint configuration
  • Use Prettier for formatting
  • Write tests for new features