文件系统MCP服务器

@cyanheads/filesystem-mcp-server
3 Stars 2.5k 次浏览 cyanheads 更新于 2026-08-23

一种模型上下文协议服务器,为人工智能代理提供对本地文件系统操作的安全访问,通过标准化接口实现文件的读取、写入和管理。

该服务暂未提供标准配置,请参考 README 手动接入

服务介绍

文件系统 MCP 服务器

TypeScript
模型上下文协议
版本
许可证
状态
GitHub

赋予您的 AI 代理强大且与平台无关的文件系统功能。

模型上下文协议 (MCP) 服务器为 AI 代理提供了一个安全可靠的接口,以与本地文件系统进行交互。它支持读取、写入、更新和管理文件及目录,并基于生产就绪的 TypeScript 基础,具备全面的日志记录、错误处理和安全措施。

目录

概述

模型上下文协议 (MCP) 是一个标准框架,允许 AI 模型安全地与外部工具和数据源(资源)进行交互。此服务器实现了 MCP 标准,将基本的文件系统操作作为工具公开,使 AI 代理能够:

  • 读取并分析文件内容。
  • 创建、修改或覆盖文件。
  • 管理目录和文件路径。
  • 在文件中执行有针对性的更新。

该服务器使用 TypeScript 构建,强调类型安全、模块化和强大的错误处理,使其适合可靠地集成到 AI 工作流中。

架构

服务器采用分层架构,以提高清晰度和可维护性:

flowchart TB
    subgraph API["API Layer"]
        direction LR
        MCP["MCP Protocol Interface"]
        Val["Input Validation (Zod)"]
        San["Path Sanitization"]

        MCP --> Val --> San
    end

    subgraph Core["Core Services"]
        direction LR
        Config["Configuration"]
        Logger["Logging (Winston)"]
        Error["Error Handling"]
        Server["MCP Server Logic"]
        State["Session State"]

        Config --> Server
        Logger --> Server & Error
        Error --> Server
        State --> Server
    end

    subgraph Implementation["Tool Implementation"]
        direction LR
        ToolLogic["Filesystem Tools"]
        Utils["Core Utilities"]

        ToolLogic --> Server
        Utils -- Used by --> ToolLogic
        Utils -- Used by --> Core
    end

    San --> ToolLogic

    classDef layer fill:#2d3748,stroke:#4299e1,stroke-width:3px,rx:5,color:#fff
    classDef component fill:#1a202c,stroke:#a0aec0,stroke-width:2px,rx:3,color:#fff
    class API,Core,Implementation layer
    class MCP,Val,San,Config,Logger,Error,Server,State,ToolLogic,Utils component
  • API 层: 处理 MCP 通信,使用 Zod 验证输入,并清理路径。
  • 核心服务: 管理配置、日志记录、错误报告、会话状态(如默认工作目录)以及主要的 MCP 服务器实例。
  • 工具实现: 包含每个文件系统工具的具体逻辑,利用共享工具。

特性

  • 全面的文件操作:用于读取、写入、列出、删除、移动和复制文件及目录的工具。
  • 针对性更新update_file 工具允许在文件中进行精确的搜索和替换操作,支持纯文本和正则表达式。
  • 会话感知路径管理set_filesystem_default 工具为会话期间解析相对路径设置默认工作目录。
  • 安全第一:内置路径清理功能防止目录遍历攻击。可选的基本目录限制进一步增强安全性。
  • 强大的基础:包括生产级实用程序:
    • 结构化、上下文感知的日志记录。
    • 标准化的错误处理,带有特定的错误代码。
    • 用于请求跟踪的独特 ID 生成。
    • 输入清理。
    • 可选的速率限制(已创建 util 文件但尚未集成)。
  • 类型安全:完全使用 TypeScript 实现,以提高可靠性和可维护性。

安装

步骤

  1. 克隆仓库:
    git clone https://github.com/cyanheads/filesystem-mcp-server.git
    cd filesystem-mcp-server
    
  2. 安装依赖项:
    npm install
    
  3. 构建项目:
    npm run build
    
    这将把 TypeScript 代码编译成 JavaScript 并存储在 dist/ 目录下,并使主脚本可执行。可执行文件位于 dist/index.js

配置

使用环境变量配置服务器:

  • FS_BASE_DIRECTORY(可选,推荐用于安全):
    • 如果设置为绝对路径,则服务器执行的所有文件操作将严格限制在此目录及其子目录内。这可以防止 AI 代理访问预期范围外的文件。
    • 示例:FS_BASE_DIRECTORY=/Users/casey/safe-agent-files
  • LOG_LEVEL(可选):
    • 控制日志的详细程度。选项:errorwarninfohttpverbosedebugsilly
    • 默认值为 info
  • LOG_DIR(可选):
    • 指定日志文件(combined.logerror.log)的存储目录。
    • 默认值为相对于服务器执行目录的 ./logs

与 MCP 客户端一起使用

要让 MCP 客户端(如 AI 助手)使用此服务器:

  1. 运行服务器: 从终端启动服务器:

    node dist/index.js
    # 或者如果你在项目根目录下:
    # npm start
    
  2. 配置客户端: 将服务器添加到你的MCP客户端的配置中。具体方法取决于客户端,但通常涉及指定以下内容:

    • 命令: node
    • 参数: 构建后的服务器可执行文件的绝对路径(例如,/path/to/filesystem-mcp-server/dist/index.js)。
    • 环境变量(可选): 根据需要设置FS_BASE_DIRECTORYLOG_LEVELLOG_DIR

    示例MCP设置(概念性):

    {
      "mcpServers": {
        "filesystem": {
          "command": "node",
          "args": ["/path/to/filesystem-mcp-server/dist/index.js"],
          "env": {
            "FS_BASE_DIRECTORY": "/path/to/base/directory",
            "LOG_LEVEL": "debug"
          },
          "disabled": false,
          "autoApprove": []
        }
        // ... 其他服务器
      }
    }
    

一旦配置并运行,客户端将检测到服务器及其可用工具。

可用工具

服务器提供了以下用于文件系统交互的工具:

Tool Description
set_filesystem_default Sets a default absolute path for the current session. Relative paths used in subsequent tool calls will be resolved against this default. Resets on server restart.
read_file Reads the entire content of a specified file as UTF-8 text. Accepts relative (resolved against default) or absolute paths.
write_file Writes content to a specified file. Creates the file (and necessary parent directories) if it doesn't exist, or overwrites it if it does. Accepts relative or absolute paths.
update_file Performs targeted search-and-replace operations within an existing file using an array of {search, replace} blocks. Ideal for localized changes. Supports plain text or regex search (useRegex: true) and replacing all occurrences (replaceAll: true). Accepts relative or absolute paths. File must exist.
list_files Lists files and directories within a specified path. Options include recursive listing (includeNested: true) and limiting the number of entries (maxEntries). Returns a formatted tree structure. Accepts relative or absolute paths.
delete_file Permanently removes a specific file. Accepts relative or absolute paths.
delete_directory Permanently removes a directory. Use recursive: true to remove non-empty directories and their contents (use with caution!). Accepts relative or absolute paths.
create_directory Creates a new directory at the specified path. By default (create_parents: true), it also creates any necessary parent directories. Accepts relative or absolute paths.
move_path Moves or renames a file or directory from a source path to a destination path. Accepts relative or absolute paths for both.
copy_path Copies a file or directory from a source path to a destination path. For directories, it copies recursively by default (recursive: true). Accepts relative or absolute paths.

请参阅工具注册文件 (src/mcp-server/tools/*/registration.ts) 以获取详细的输入/输出模式 (Zod/JSON Schema)。

项目结构

代码库组织清晰,便于维护:

filesystem-mcp-server/
├── dist/                 # Compiled JavaScript output (after npm run build)
├── logs/                 # Log files (created at runtime)
├── node_modules/         # Project dependencies
├── src/                  # TypeScript source code
│   ├── config/           # Configuration loading (index.ts)
│   ├── mcp-server/       # Core MCP server logic
│   │   ├── server.ts     # Server initialization and tool registration
│   │   ├── state.ts      # Session state management (e.g., default path)
│   │   └── tools/        # Individual tool implementations (one subdir per tool)
│   │       ├── readFile/
│   │       │   ├── index.ts
│   │       │   ├── readFileLogic.ts
│   │       │   └── registration.ts
│   │       └── ...       # Other tools (writeFile, updateFile, etc.)
│   ├── types-global/     # Shared TypeScript types and interfaces
│   │   ├── errors.ts     # Custom error classes and codes
│   │   ├── mcp.ts        # MCP related types
│   │   └── tool.ts       # Tool definition types
│   ├── utils/            # Reusable utility modules
│   │   ├── errorHandler.ts
│   │   ├── idGenerator.ts
│   │   ├── index.ts
│   │   ├── logger.ts
│   │   ├── rateLimiter.ts
│   │   ├── requestContext.ts
│   │   └── sanitization.ts
│   └── index.ts          # Main application entry point
├── .clinerules           # Cheatsheet for LLM assistants
├── .gitignore
├── LICENSE
├── package.json
├── package-lock.json
├── README.md             # This file
└── tsconfig.json         # TypeScript compiler options

要查看当前结构的实时详细视图,请运行:npm run tree

开发者注意: 该仓库包含一个 .clinerules 文件。这个速查表为您的 LLM 编码助手提供了关于代码库模式、文件位置和使用示例的重要上下文。随着服务器的发展,请保持其更新!

许可证

本项目根据 Apache License 2.0 许可。有关详细信息,请参见 LICENSE 文件。


相关 MCP 服务