Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

环境与安装

需要 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/ 里的文件。

参考文档

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages