Skip to main content
Glama
Ruadgedy

filesystem

by Ruadgedy

MCP 入门案例:文件操作 Server

一个最小可运行的 MCP(Model Context Protocol)Server,用 Python 官方 v2 SDK 写成, 暴露三个文件操作工具,供 MCP Inspector 调试验证。

MCP 三层架构速记

┌──────────────┐   stdio/HTTP   ┌──────────┐   子进程   ┌──────────────────┐
│   Host       │◀─────────────▶│  Client  │◀──────────▶│  Server (本项目)  │
│ Claude Desktop│               │(Host 内部)│  stdin/stdout│  filesystem.py   │
│  Inspector   │               │          │            │  暴露 Tools/...   │
└──────────────┘               └──────────┘            └──────────────────┘
  • Host:跑大模型的应用(Claude Desktop、Inspector 等),内部管理 Client。

  • Client:与某个 Server 建立 1:1 连接,按 MCP 协议收发消息。

  • Server:你写的程序,向模型暴露三类能力。本例只用了最常用的 Tool

    • read_file / write_file / list_directory

Related MCP server: files-mcp-ts

环境与安装

需要 Python ≥ 3.10(本机用 3.13)和 uv。依赖已写在 pyproject.toml

uv sync          # 安装依赖、创建虚拟环境

核心依赖是 mcp[cli]>=2.0.0(v2 用 MCPServer 取代了旧版 FastMCP)。

用 MCP Inspector 调试

Inspector 是官方图形化工具,能直接看到模型/客户端如何调用你的工具,无需配置 Claude Desktop。

uv run mcp dev servers/filesystem.py

启动后会打印一个本地网址(默认 http://127.0.0.1:6274 ),浏览器打开即可。在左侧 “Tools” 里能看到三个工具,点开 -> 填参数 -> 点 “Run Tool” 看返回。

建议按这个顺序试一遍,体会完整流程:

  1. list_directory(path 留空走默认 .)-> 应看到 hello.txt

  2. read_file,path 填 hello.txt -> 读到示例内容

  3. write_file,path 填 test.txt、content 随便写 -> 提示写入成功

  4. list_directory -> 应看到新增的 test.txt

  5. 安全测试:read_file path 填 ../secret -> 应被拒绝(沙箱拦截路径穿越)

程序化验证(不走 Inspector)

不启动 Inspector,用 v2 内存 Client 直接连 server 对象跑一遍工具,适合快速回归:

uv run python tests/test_filesystem.py
# 或:uv run python -m tests.test_filesystem

目录结构

mcp-test/
├── pyproject.toml          # uv 项目 + 依赖声明
├── uv.lock                 # 依赖锁文件(提交进 git 保证可复现)
├── servers/
│   └── filesystem.py       # MCP Server:三个文件操作 Tool
├── tests/
│   └── test_filesystem.py  # 冒烟测试(内存 Client 直连)
├── workspace/              # 沙箱目录,所有文件操作只能在此内进行
│   └── hello.txt           # 示例文件(运行时产生的文件被 .gitignore 忽略)
└── README.md

所有工具的路径都解析到 workspace/ 之内,并用 resolve() + 父目录校验拦截 ../ 之类的路径穿越。这是 MCP Server 编写的安全要点:永远校验模型传进来的路径

关键代码点

  • from mcp.server import MCPServer - v2 的入口(不是旧版 mcp.server.fastmcp.FastMCP

  • @mcp.tool() 装饰一个普通函数 - 函数名、docstring、类型注解就是工具的全部元数据

  • if __name__ == "__main__": mcp.run() - 无参数即 stdio 传输;守卫不可省, 因为 mcp dev 会先 import 本文件

  • 调试走 logging(输出到 stderr)- stdio 模式下 stdout 是协议链路,不能用 print

下一步

把 Server 接入 Claude Desktop,在真实对话里用上它:

uv run mcp install servers/filesystem.py --name "filesystem"

这会自动写入 Claude Desktop 的 claude_desktop_config.json,重启 Desktop 后即可在对话中 让模型读写 workspace/ 里的文件。

参考文档

Available Tools

3 tools
list_directoryA

列出 workspace 内某个目录下的条目,每行标注 FILE 或 DIR。

Args: path: 相对于 workspace 的目录路径,默认为 workspace 根目录。

ParametersJSON Schema
NameRequiredDescriptionDefault
pathNo.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description discloses the output format (FILE or DIR labeling) but does not specify behavior for edge cases like nonexistent paths, hidden files, or recursion. With no annotations, the description carries the transparency burden but only partially fulfills it.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the tool's purpose and supplemented with parameter details. It is concise with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has a single parameter and an output schema, and the description covers the core usage. However, it lacks details about error handling and listing scope (e.g., recursive), though the simplicity of the tool mitigates this gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description includes an Args section explaining that the 'path' parameter is a directory path relative to the workspace, defaulting to the workspace root. This adds semantic meaning absent from the input schema, which has no description and only a default of '.'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool lists directory entries in the workspace and labels each entry as FILE or DIR, distinguishing it from sibling file read/write tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool over read_file or write_file, nor any prerequisites or exclusions. The description only covers basic usage with the path argument.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

read_fileA

读取 workspace 内某个文本文件的内容并返回。

Args: path: 相对于 workspace 的文件路径,例如 "hello.txt" 或 "notes/a.txt"。

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must carry the behavioral burden. It adds useful context about the path being relative to the workspace, but does not disclose error handling, file encoding, or side effects. Since this is a read-only operation, the absence of mutation details is acceptable, but the lack of error/edge-case info leaves a gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise, with a single-purpose sentence and a brief parameter explanation. It is front-loaded with the action and contains no unnecessary words or repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple read tool with one parameter and an output schema, the description covers the essential context: what is read, from where, and how to specify the path. It lacks details on failure modes, but the presence of an output schema reduces the burden of explaining return behavior. Overall, it is sufficiently complete for the tool's simplicity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description fully compensates by explaining the 'path' parameter with a clear definition (relative to workspace) and examples. This adds significant meaning beyond the schema's bare 'Path' property, making the parameter semantics very clear.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('读取' meaning read) and resource ('workspace 内某个文本文件' meaning text file in the workspace), clearly distinguishing it from siblings like write_file and list_directory. It states the function is to read content and return it, which is unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by stating it reads files from the workspace, but it does not explicitly mention when to use this tool versus alternatives. No exclusions or alternative tool names are provided, though the sibling names (write_file, list_directory) make the context somewhat clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

write_fileA

把文本内容写入 workspace 内的文件;文件或上级目录不存在则自动创建。

Args: path: 相对于 workspace 的文件路径。 content: 要写入的文本,会整体覆盖已有内容。

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes
contentYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description discloses key behavioral traits: automatic creation of missing files/parent directories, and full overwriting of existing content. Since no annotations are provided, these details are crucial and are adequately covered. It also constrains the path to be workspace-relative.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise, consisting of a one-sentence overview plus brief parameter explanations. No redundant information is present; every sentence is informative.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity, the description adequately covers the core behavior: writing content, handling missing paths, and overwriting semantics. The presence of an output schema means return values are already specified externally, so no additional return-value detail is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates by explaining both parameters: path is relative to workspace, and content is the text to write (overwriting existing). This provides essential meaning beyond the bare schema types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action: writing text content into a workspace file, with specific mention of auto-creating missing paths and overwriting existing content. This distinguishes it from sibling tools like read_file and list_directory.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description does not explicitly state when to use this tool versus alternatives, nor does it mention exclusions (e.g., when not to use). While the tool's function is implied, there is no direct guidance on choosing it over read_file or list_directory, though the context is clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A3.9/5.0
Disambiguation5/5

Each tool has a single, clear purpose: reading, writing, or listing. There is no overlap between these operations, so an agent can easily select the correct tool.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern: read_file, write_file, list_directory. This makes the API predictable and easy to remember.

Tool Count3/5

Three tools is a minimal set. While it covers basic file operations, a typical filesystem server would also include delete, rename, or move operations, making the count feel thin for the advertised scope.

Completeness2/5

The server lacks common filesystem operations such as delete, rename, move, and directory creation. This is a significant gap; for example, an agent cannot clean up or reorganize files after creating them.

Maintenance

ActivityMaintained
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    An MCP server that provides tools for secure file management within a dedicated workspace directory. It enables users to create, list, and delete files through natural language while preventing path traversal attacks.
    28
  • F
    license
    B
    quality
    D
    maintenance
    A lightweight MCP server for basic file operations, enabling reading, writing, and listing files securely via the Model Context Protocol.
    3
    1

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Ruadgedy/mcp-test'

If you have feedback or need assistance with the MCP directory API, please join our Discord server