文件读取工具

一个基于MCP协议的文件读取服务器和客户端,支持多种文件格式的读取和内容返回。

  • by ShivaniShah0218
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 ShivaniShah0218/mcp-python-playground

使用说明

MCP Python游乐场

一个最小的MCP(消息/方法调用协议)文件读取器服务器和一个调用它的客户端 read_file 该工具读取不同的文件格式,并通过MCP传输(默认为stdio)返回内容。客户端演示如何调用工具并处理响应。

特性

  • 读取多种文件格式:
    • .txt, .csv, .docx, .json, .pdf, .xlsx
  • 位于 readers/ 目录(每种格式一个阅读器)。
  • 用途 mcp 框架并运行服务器 transport="stdio" 默认情况下。
  • 异步MCP客户端 client.py 它使用stdio启动并与服务器通信。

需求

从安装依赖项 requirements.txt:

关键依赖关系:

  • mcp --用于创建服务器/客户端的MCP框架
  • pydantic --请求/响应验证
  • PyPDF2, python-docx, pandas, openpyxl --PDF、DOCX、Excel、CSV的后端
  • fpdf --(可选)PDF生成/测试

项目布局

  • server.py --MCP服务器正在注册 read_file 工具。
  • client.py --异步MCP客户端,启动服务器并调用 read_file.
  • readers/ --阅读器模块: txt.py, csv.py, docx.py, json.py, pdf.py, xlsx.py.
  • test_files/ --(不包括在内)将示例文件放在此处进行测试。
  • requirements.txt, .gitignore, README.md

用法

  1. 确保安装了依赖项:

  2. 运行客户端以调用服务器并读取文件:


`client.py` will:
   - Launch the server as a subprocess using stdio transport
   - Initialize an MCP session
   - Call `read_file` for each file found in `test_files/`
   - Log previews (first 200 chars) of file contents to `client.log`

The server registers the `read_file` tool:
- Input model: `ReadFileInput` with `path: str`
- Tool name: `read_file`
- Returns file content as `str` or an error message string.

## Extending / Adding formats

1. Add a new reader function under `readers/`, e.g. `readers/markdown.py` with `def read_markdown(path: str) -> str`.
2. Import and map the extension in `server.py`:

如果您计划添加多种格式,请考虑集中扩展->处理程序映射。

故障排除

  • 如果阅读器出现故障,请检查 client.log 用于客户端日志和检查 server.log stdout/stderr用于服务器错误。
  • 确保文件依赖性(例如。, python-docx, PyPDF2)已安装并与您的Python版本兼容。