convez.ai
MCP ServerDevOps & InfraestruturaIntermediário
wonker007

SurgicalFS MCP Server

wonker007/surgicalfs-mcpserver

Filesystem MCP otimizado para economizar tokens com leituras parciais e estruturadas

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP de sistema de arquivos de alta performance, construído em Rust com otimização agressiva de contexto. Substitui o servidor padrão oferecendo leitura parcial, suporte a formatos estruturados (JSON, CSV, XLSX, PDF, DOCX) e orçamento de resposta para economizar tokens do contexto.

Instalação

$npx convez-ai wonker007/surgicalfs-mcpserver

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
5
Forks
0
Acompanhando
1
Saúde
42%
Último commit
há 4 meses
Versão
—
Issues abertas
1
Contribuidores
1

Casos de uso

  • Operações de leitura e escrita eficientes em projetos grandes sem poluição de contexto
  • Integração com IDEs e clientes MCP (Claude Desktop, Cursor, VS Code, Zed)
  • Processamento de arquivos estruturados com queries JSON e filtros CSV
  • Desenvolvimento local com segurança reforçada e path allowlist

Veredito

Solução técnica sólida e bem pensada para um problema real: vazamento de contexto em operações de filesystem. A ênfase em economia de tokens e operações cirúrgicas é genuína. Implementação em Rust garante performance, mas requer compilação — setup mais exigente que alternativas Node.js.

README

A tradução para o português deste README ainda está na fila.

SurgicalFS MCP Server

High-performance, context-efficient filesystem MCP server built in Rust. Designed as a drop-in replacement for the default @modelcontextprotocol/server-filesystem — with surgical read/write operations, structured file format support, and aggressive context window optimization.

Version: 0.4.2 · 47 tools · Rust + rmcp SDK · Windows-first, cross-platform compatible

Works with any MCP-compatible client: Claude Desktop, Claude Code, Cursor, VS Code, Windsurf, Zed, ChatGPT (via remote MCP), Gemini, and more.


Why SurgicalFS?

The default MCP filesystem server has several limitations that become painful in real-world usage:

  • Context pollution — read_file dumps entire file contents into the conversation, burning tokens on irrelevant lines
  • No partial editing — every edit requires reading the full file, modifying it, and writing it back
  • Slow cold-start — Node.js process spins up on every invocation
  • Security gaps — known path traversal CVEs (CVE-2025-53109, CVE-2025-53110) in the reference implementation
  • No structured formats — no native support for JSON queries, CSV filtering, XLSX/PDF/DOCX extraction

SurgicalFS addresses all of these with a single compiled binary that starts instantly, enforces a path allowlist, and provides tools designed to minimize context window usage at every level.

Design Philosophy: Context Economy

Every tool in SurgicalFS is designed around a single principle: never put bytes into the context window that don't need to be there.

  • Read tools support head/tail/line-range access — never load a full file when you need 10 lines
  • Mutation tools return compact summaries (line numbers, counts), never the modified file content
  • Search tools offer tiered verbosity: full → lines → count, from richest to cheapest
  • A server-side response budget hard-caps every response before it enters the conversation
  • Write strategies guide the model toward chunked writes, staging files, and batch edits to avoid repeating content
  • Tool descriptions embed context hygiene directives that steer LLM behavior at the protocol level

How It Compares

ServerToolsEst. definition tokensPartial readsStructured formatsResponse budget
Official filesystem14~1,500NoNoNo
Desktop Commander~25~8,000No (full reads)XLSX/PDF/DOCXNo
safurrier/mcp-filesystem~20~4,000YesNoNo
SurgicalFS (all tools)47~14,000YesJSON/CSV/XLSX/PDF/DOCXYes
SurgicalFS (core only)~17~5,000YesNoYes

SurgicalFS costs more upfront in tool definitions, but recoups it on the first operation. A single read_file call on a 200-line file through the official server dumps ~800 tokens; SurgicalFS's file_head with 20 lines returns ~100 tokens. Over a typical coding session, the response-side savings far exceed the definition overhead.

Tip: If tool definition overhead is a concern, disable unnecessary categories via config. See Tool Categories & Config-Driven Profiles.


Installation

Build from source

cargo build --release

Binary location depends on your toolchain. With the GNU target (recommended on Windows):

target/x86_64-pc-windows-gnu/release/surgicalfs-mcp.exe

On Linux/macOS with the default target:

target/release/surgicalfs-mcp

Configure for your MCP client

SurgicalFS uses stdio transport (JSON-RPC over stdin/stdout), which is the standard for local MCP servers. The configuration pattern is the same across clients: point the client at the binary and optionally specify a config file.

Claude Desktop

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "surgicalfs": {
      "command": "/path/to/surgicalfs-mcp",
      "args": []
    }
  }
}

Config file locations:

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

Claude Code

claude mcp add surgicalfs -- /path/to/surgicalfs-mcp

Cursor

Add to Cursor Settings → MCP, or in .cursor/mcp.json:

{
  "mcpServers": {
    "surgicalfs": {
      "command": "/path/to/surgicalfs-mcp",
      "args": []
    }
  }
}

VS Code (Copilot)

Add to .vscode/mcp.json (per-workspace) or user mcp.json:

{
  "servers": {
    "surgicalfs": {
      "command": "/path/to/surgicalfs-mcp",
      "args": []
    }
  }
}

Windsurf

Add to ~/.windsurf/mcp.json or the project-level equivalent:

{
  "mcpServers": {
    "surgicalfs": {
      "command": "/path/to/surgicalfs-mcp",
      "args": []
    }
  }
}

Zed

Add to Zed's settings under context_servers:

{
  "context_servers": {
    "surgicalfs": {
      "command": {
        "path": "/path/to/surgicalfs-mcp",
        "args": []
      }
    }
  }
}

Remote access (ChatGPT, Gemini, claude.ai web/mobile, and other HTTP clients)

SurgicalFS uses stdio transport natively. To expose it over HTTP for web-based clients, use supergateway to bridge stdio to streamable HTTP, then put it behind a reverse tunnel (Cloudflare Tunnel, ngrok, etc.):

npx supergateway --stdio "/path/to/surgicalfs-mcp" --port 8080 --outputTransport streamableHttp

Then point your tunnel at localhost:8080 and register the public URL in your client's MCP integration settings.

Windows + stateless gateways — prevent orphaned processes: In supergateway's default stateless streamableHttp mode, a fresh server process is spawned per request and is not reliably reaped on Windows (the gateway's child.kill() targets the cmd.exe shell wrapper, and it never closes the child's stdin — so stdin-EOF never arrives while the gateway is alive). These children accumulate until the gateway exhausts its handles and the endpoint goes dark. Pass --idle-timeout-secs so each child self-reaps once idle:

npx supergateway --stdio "/path/to/surgicalfs-mcp --idle-timeout-secs 30" --port 8080 --outputTransport streamableHttp

Use a small value (e.g. 30) for stateless mode, where each child is single-shot. For --stateful supergateway (one reused process per session), use a value larger than the longest expected mid-conversation pause (e.g. 600) so a session isn't reaped during think-time.

Note: AI providers make outbound connections to your MCP endpoint — localhost URLs won't work from hosted clients. A tunnel or public-facing server is required.

Security: MCP over HTTP has no built-in authentication. Anyone who discovers your tunnel URL can call any tool and read/write files within your allowed directories. Secure your tunnel with IP allowlisting (e.g., Cloudflare WAF rules restricting to your AI provider's IP ranges), VPN, or equivalent access controls before exposing to the internet. The --read-only flag provides an additional safety layer for remote deployments.


Configuration

Open configure.html in your browser for an interactive config generator — toggle tool categories, see live token cost estimates, and copy the generated TOML and client registration snippets.

SurgicalFS looks for surgicalfs.toml in this order:

  1. Next to the executable
  2. Platform config directory:
    • Windows: %APPDATA%\surgicalfs-mcp\config.toml
    • macOS/Linux: ~/.config/surgicalfs-mcp/config.toml
  3. Explicit path: surgicalfs-mcp --config /path/to/surgicalfs.toml

Full configuration reference

[security]
# REQUIRED: directories the server is allowed to access.
# All path operations are validated against this allowlist.
# Symlinks that resolve outside these directories are blocked.
allowed_directories = ["/home/yourname/projects"]
follow_symlinks = false        # default: false
max_file_size = 5242880        # bytes, default: 5MB

[search]
ripgrep_path = "auto"          # "auto" (PATH → beside exe → native fallback), or explicit path
max_results = 100              # default cap for search results
default_context_lines = 2      # lines of context around matches

[defaults]
head_lines = 50                # default for file_head
tail_lines = 50                # default for file_tail
max_read_lines = 500           # cap for file_read_lines range
encoding = "auto"              # "auto", "utf-8", "windows-1252"

[response_budget]
max_response_lines = 200       # hard cap on response line count
max_response_bytes = 32768     # hard cap on response byte size (32KB)
truncation_mode = "smart"      # "smart" (break at newline) or "hard" (exact byte cut)

[runtime]
idle_timeout_secs = 0          # self-exit after N idle seconds (0 = never).
                               # Leave 0 for local stdio clients. Set >0 only for
                               # remote supergateway deployments to reap orphaned
                               # children (see Remote access above). CLI override:
                               # surgicalfs-mcp --idle-timeout-secs 30

Tools Reference

SurgicalFS provides 47 tools across 11 categories: surgical operations purpose-built for context efficiency, plus a backwards-compatible layer that mirrors the default MCP filesystem server.

Inspect (4 tools)

ToolDescription
file_infoFile metadata (size, line count, encoding, timestamps) without reading content
file_headFirst N lines (default: 50) with truncation indicator
file_tailLast N lines (default: 50) with start line number
file_read_linesSpecific line range (1-indexed, inclusive)

Search (3 tools)

ToolDescription
file_searchMulti-file/directory pattern search via ripgrep. Supports return_mode: full (lines + context), lines (file:line pairs only, ~80% fewer tokens), count (matches per file, ~95% fewer tokens)
file_grepSingle-file grep returning line numbers only by default. include_content=true adds matching text. Most token-efficient way to locate patterns in a known file
file_search_replace_previewDry-run find-and-replace showing before/after diffs without modifying the file

Mutate (5 tools)

ToolDescription
file_replaceIn-place find-and-replace (literal or regex). Returns change count + line numbers, never file content. Supports multi-line patterns with \r\n normalization
file_insertInsert text at a line number, or before/after a pattern match. Accepts anchor as object or JSON string
file_appendAppend text to end of file
file_patch_linesReplace a line range with new content
file_batch_editMultiple edits in one atomic operation. ~90% less context than individual calls for 3+ edits

JSON (2 tools)

ToolDescription
json_queryJSONPath queries (RFC 9535) returning matched nodes only
json_mutateModify JSON at JSONPath locations (set, delete, insert, append)

CSV (4 tools)

ToolDescription
csv_infoColumn names, row count, detected delimiter
csv_readRead specific rows and/or columns
csv_queryFilter rows by column value (eq, neq, contains, gt, lt, gte, lte, regex)
csv_writeCreate new CSV or append rows to existing

Documents (3 tools)

ToolDescription
pdf_infoPage count and file size without extracting text
pdf_extractExtract text by page range, one string per page
docx_extractExtract text from .docx with offset/max_chars pagination

Spreadsheets (3 tools)

ToolDescription
xlsx_infoSheet names and dimensions for .xlsx, .xls, .ods
xlsx_readRead cells by sheet and range (Excel notation, e.g., B2:D10)
xlsx_querySearch for values across sheets without loading full data

File Management (6 tools)

ToolDescription
file_writeCreate/overwrite a file (recommended for <50 lines)
file_write_chunkedVerified chunked writes for large files. Sessions persist to disk for stateless transports
file_write_streamAtomic copy/move of a staging file to final destination with optional SHA-256 verification
file_copyDisk-to-disk copy — content never enters the conversation
file_deleteDelete a file
file_moveMove or rename a file

Directory (2 tools)

ToolDescription
directory_listList contents with metadata, glob filtering, depth control, sorting
directory_treeASCII tree visualization with optional file sizes

Utility (1 tool)

ToolDescription
file_checksumSHA-256, MD5, or BLAKE3 checksum without reading file into context

Backwards-Compatible Layer (14 tools)

Drop-in replacements for every tool in the default @modelcontextprotocol/server-filesystem, so existing workflows and prompts continue to work unchanged:

read_file, read_text_file, read_media_file, read_multiple_files, write_file, edit_file, create_directory, list_directory, list_directory_with_sizes, directory_tree_compat, move_file, search_files, get_file_info, list_allowed_directories

Tool descriptions in the compat layer steer the model toward the surgical alternatives (e.g., read_file's description suggests file_read_lines or file_head for large files).


Tool Categories & Config-Driven Profiles

MCP tool definitions consume context window tokens on every interaction — typically 250–500 tokens per tool. With 47 tools, SurgicalFS costs roughly 14,000 tokens of definition overhead. While this is modest compared to servers like GitHub MCP (~55,000 tokens for 93 tools), it can matter in token-constrained environments.

Some clients implement deferred tool loading (e.g., claude.ai's tool search), which avoids upfront injection. But most clients — including Cursor, VS Code, and ChatGPT — load all definitions eagerly.

Note: Cursor enforces a hard limit of 40 tools. SurgicalFS's full catalog of 47 exceeds this. Use a profile to stay within client limits.

Profiles

Configure which tool categories are registered via surgicalfs.toml:

[tools]
# Only register these categories in tools/list
enable = ["inspect", "search", "mutate", "manage", "directory", "utility"]
# Omitted categories won't appear in the tool catalog at all.
# Categories: inspect, search, mutate, json, csv, document, spreadsheet,
#             manage, directory, utility, compat
ProfileCategoriesToolsEst. tokens
Full (default)All 1147~14,000
Coreinspect, search, mutate, manage, directory, utility~17~5,000
Core + formatsCore + json, csv, document, spreadsheet~29~9,000
Compat onlycompat14~4,000

This gives you granular control over the cost/capability tradeoff. Users who don't need XLSX parsing, the compat layer, or CSV operations simply don't pay for them.


Token Efficiency Guide

SurgicalFS provides multiple verbosity tiers for search operations, letting you trade detail for token savings:

file_search return modes

return_modeResponse shapeToken cost
full (default)Matching lines with surrounding contextHigh
lines{file, line} pairs only~80% less
countMatch count per file~95% less

file_grep modes

ModeResponse shapeToken cost
DefaultLine numbers only: [5, 12, 89]Minimal
include_content=true{line, content} pairsLow

search_files limiting

Set max_results to cap glob results (default can return up to 200 paths).

Write strategy selection

ScenarioRecommended toolWhy
New file, <50 linesfile_writeSingle call, simple
New file, 50+ linesfile_write_chunkedVerified chunks, no re-output
Assembled from sourcesfile_append → file_write_streamBuild staging file, then promote
Edit 1–2 locationsfile_replace or file_insertReturns summary, not content
Edit 3+ locationsfile_batch_edit~90% less context than individual calls
Duplicate existing filefile_copyZero context cost

Architecture

src/
├── main.rs              # CLI parsing, config loading, server startup
├── config.rs            # TOML config types and defaults
├── server.rs            # MCP ServerHandler with #[tool_router] + #[tool_handler]
├── pathguard.rs         # Security: path allowlist, symlink blocking, size guards
├── encoding.rs          # BOM detection, UTF-8/Windows-1252 fallback
├── search_backend.rs    # ripgrep (preferred) / native Rust (fallback) search
├── response_budget.rs   # Hard response truncation (char-boundary safe)
├── errors.rs            # Structured errors with suggestions
└── tools/
    ├── inspect.rs       # file_info, file_head, file_tail, file_read_lines
    ├── search.rs        # file_search, file_grep, file_search_replace_preview
    ├── mutate.rs        # file_replace, file_insert, file_append, file_patch_lines, file_batch_edit
    ├── json_ops.rs      # json_query, json_mutate
    ├── csv_ops.rs       # csv_info, csv_read, csv_query, csv_write
    ├── document.rs      # pdf_info, pdf_extract, docx_extract
    ├── spreadsheet.rs   # xlsx_info, xlsx_read, xlsx_query
    ├── manage.rs        # file_write, file_write_chunked, file_write_stream, file_copy, file_delete, file_move
    ├── directory.rs     # directory_list, directory_tree
    ├── utility.rs       # file_checksum
    └── compat.rs        # 14 backwards-compatible tools matching default MCP filesystem server

Security Model

  • Path allowlist — every operation validates paths against allowed_directories before any I/O
  • Symlink blocking — symlinks resolving outside allowed directories are rejected (configurable)
  • File size guard — configurable max_file_size prevents accidental reads of huge files
  • Case-insensitive paths — Windows drive letters and paths handled correctly via dunce
  • No unsafe blocks — zero unsafe Rust in the entire codebase
  • Zero cargo audit advisories — no known dependency vulnerabilities

Search Backend

SurgicalFS auto-detects ripgrep for maximum search performance:

  1. Checks PATH for rg
  2. Checks next to the SurgicalFS binary
  3. Falls back to a native Rust search backend (regex + walkdir)

The fallback is fully functional but slower on large directory trees. Bundling rg (or rg.exe) next to the SurgicalFS binary is recommended for best performance.

Response Budget

Every tool response passes through a server-side budget filter before being sent via MCP:

  • max_response_lines — hard line count cap
  • max_response_bytes — hard byte size cap
  • truncation_mode — smart (break at nearest newline) or hard (exact byte cut, char-boundary safe)

This ensures that even if a tool produces a large result, the context window impact is bounded. No other filesystem MCP server provides this.


Development

cargo build              # Debug build
cargo build --release    # Optimized, stripped, LTO-enabled release build
cargo test               # Run all tests (~145 tests)
cargo clippy             # Lint (zero warnings policy)
cargo fmt                # Format
cargo audit              # Dependency vulnerability scan (zero advisories)

Build profile

The release profile is tuned for minimal binary size and maximum performance:

[profile.release]
opt-level = 3
lto = true
strip = true
codegen-units = 1

Key Dependencies

CratePurpose
rmcpRust MCP SDK (server mode, stdio transport)
serde_json_pathJSONPath RFC 9535 queries
calamineXLSX/XLS/ODS spreadsheet reading
pdf-extractPDF text extraction
dotextDOCX text extraction
csvCSV parsing and writing
regexPattern matching
walkdirDirectory traversal
dunceWindows-safe path canonicalization
sha2, md-5, blake3Checksums
encoding_rsEncoding detection and conversion
clapCLI argument parsing

Version History

VersionChanges
v0.4.2Idle self-reap to prevent orphaned processes behind stateless supergateway on Windows. New [runtime] idle_timeout_secs config + --idle-timeout-secs CLI flag (default 0 = off; local clients unaffected). Lifecycle logic consolidated into src/lifecycle.rs with an in-flight guard so a process is never reaped mid-response.
v0.4.1Security audit fixes: integer overflow in file_grep pagination (switched to saturating_add). Config validation for empty/invalid tool category names. Updated tool descriptions for expected_content. Edge case tests for CRLF content verification and overflow saturation.
v0.4.0Config-driven tool categories ([tools] enable). .gitignore support via ignore crate. --read-only CLI flag. Search pagination (offset param). Content verification (expected_content on file_patch_lines and file_insert).
v0.3.4Fixed file_replace silently failing on multi-line find patterns (now uses whole-text matching with \r\n normalization). Fixed file_insert anchor parsing from web-based MCP clients (auto-parses JSON string anchors). Added file_grep single-file search tool. Added return_mode (full/lines/count) to file_search. Added max_results to search_files.
v0.3.3Fixed chunked write session timeout: sessions now persist to temp directory for stateless transports (e.g., supergateway streamableHttp).
v0.3.2Fixed PDF page extraction: replaced extract_text() + form-feed splitting with per-page extraction.
v0.3.1Code audit: removed dead code, fixed char-boundary panics in docx_extract and read_text_file, fixed file_insert offset bug with occurrence=all.
v0.3.0Added file_copy for disk-to-disk copy without content round-tripping.
v0.2.0Fixed tools/list returning empty array (added #[tool_handler] macro). Replaced broken PowerShell search fallback with native Rust backend. Fixed response budget truncation panic on multi-byte UTF-8.
v0.1.0Initial release. All tools implemented and tested.

Roadmap

  • MCP Roots protocol support — dynamic directory updates from clients without server restart
  • File diff tool — unified diff between two files for code review workflows
  • ZIP/archive support — create and extract archives

License

MIT License. See LICENSE for details.


Acknowledgements

Built with the Rust MCP SDK (rmcp). SurgicalFS implements the Model Context Protocol, an open standard under the Linux Foundation for connecting AI assistants to external tools and data sources.

The content verification feature (expected_content on file_patch_lines and file_insert) is inspired by safurrier/mcp-filesystem by Alex Furrier (MIT licensed).

Ver o original no GitHub

Bom para

Relacionados